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
When defining a function with the type of a TypeVar as one of the parameters and a return value of that same TypeVar, Mypy incorrectly traverses type refinement branches and throws an incompatible return value type error.
I do not expect mypy to identify issues with the code. Even though the types are narrowed, they still return correctly in conjunction with what is passed in for t, which I believe to be technically correct.
Actual Behavior
main.py:15: note: Revealed type is "type[builtins.int]"
main.py:15: note: Revealed type is "type[builtins.str]"
main.py:15: note: Revealed type is "type[builtins.bool]"
main.py:16: error: Incompatible return value type (got "bool", expected "str") [return-value]
Found 1 error in 1 file (checked 1 source file)
Workaround
A simple workaround is to just wrap the return value with a call to t. Playground example here. Even though the workaround is "simple," code modifications like this shouldn't be necessary to use a typechecker.
Environment
Mypy version used: 1.13.0
Mypy command-line flags: N/A
Mypy configuration options from mypy.ini (and other config files): N/A
Python version used: 3.12
The text was updated successfully, but these errors were encountered:
Also note that bool is a subclass of int. You should probably check for bool before int case in the fixed code to avoid taking the int branch in both cases.
When defining a function with the type of a TypeVar as one of the parameters and a return value of that same TypeVar, Mypy incorrectly traverses type refinement branches and throws an incompatible return value type error.
To Reproduce
Example A
Related variant Example B
Example C
Example A
at-a-glance:Expected Behavior
I do not expect mypy to identify issues with the code. Even though the types are narrowed, they still return correctly in conjunction with what is passed in for
t
, which I believe to be technically correct.Actual Behavior
Workaround
A simple workaround is to just wrap the return value with a call to
t
. Playground example here. Even though the workaround is "simple," code modifications like this shouldn't be necessary to use a typechecker.Environment
mypy.ini
(and other config files): N/AThe text was updated successfully, but these errors were encountered: