You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
mypy seems to forget inferred type after asigning an Any typed variable #22518
fromtypingimportAnynum=1# Statically typed (inferred to be int)num='x'# error: Incompatible types in assignment (expression has type "str", variable has type "int")dyn: Any=1# Dynamically typed (type Any)dyn='x'# OKnum=dyn# No error, mypy will let you assign a value of type Any to any variablenum+=1# Oops, mypy still thinks num is an int
the last line says, that even after assigning an Any typed value to num, mypy still holds it for an int, which is also why the example shows now typing error but the Oops because there’ll be a runtime error.
However, it seems that mypy actually does "narrow down" the inferred type to Any, which unfortunately causes all later type checking to be ignored.
foo.py:7: note: Revealed type is "Any"
foo.py:9: error: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
foo.py:13: note: Revealed type is "int"
foo.py:14: error: "int" has no attribute "nonexistent" [attr-defined]
Found 2 errors in 1 file (checked 1 source file)
So for num, whose type is inferred from its first assignment:
the inferred type int is still enforced for assignments (line 9 is an error as expected),
but after num = dyn, mypy treats num as Any, so num.nonexistent() (line 8) is not reported.
For annotated, which has an explicit annotation, mypy keeps the type int after the assignment of dyn (as described in the documentation), so annotated.nonexistent() is reported.
Expected Behavior
mypy keeps treating num as int after the assignment of an Any value, as the documentation describes and as it already does for explicitly annotated variables, or
I mean one could just update the documentation to the actual beahviour, but that seems pretty odd, as a single unexpected Any assignment could cause quite some unnoticed errors?
Your Environment
Mypy version used: 2.4.1
Mypy command-line flags: none
Mypy configuration options from mypy.ini (and other config files): none
Activity