-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Description
Feature
Hi Team,
I am not sure whether this is a bug or mypy just supporting the native python typing, but, this seems like a good add-on to tight type scoping for variables introduced in a loop local setting.
Check this Playground link.
Here, the scope (specifically, typing scope for mypy) of variable key
should be valid only for the current loop, but it goes beyond the loop:
def loop_builtin_type_infer_issue() -> None:
int_keys: list[int] = [1] # only one item included for brevity
for key in int_keys: # key is int here, correct
print(key)
str_keys: list[str] = ['no_all'] # only one item included for brevity
for key in str_keys: # <-- this is the problem area.
# mypy treats key as int here as well, taking
# the key type from the previous loop. When it should actually infer the type of key here
# as str, not int.
print(key)
Error encountered:
main.py:20: error: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
I guess if a variable is introduced in a loop then mypy should (unlike python typing) treat its type scoped to that loop and thus the type of key in the second loop should be str
not int
carried on from the previous loop.
I haven't raised it as a bug as I am not entirely sure whether this is a bug and hence, am raising it as a feature.
Please let me know your thoughts.
Pitch
Introducing this feature will make programming with loop local introduced variables more pragmatic.