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
Type narrowing fails when narrowing Optional NewType #11995
fromtypingimportUnion, NewTypeInt=NewType("Int", int)
Float=NewType("Float", float)
defraw_types(arg: Union[int, float, None]) ->None:
ifisinstance(arg, int):
reveal_type(arg) # Revealed type is "builtins.int"elifisinstance(arg, float):
reveal_type(arg) # Revealed type is "builtins.float"else:
reveal_type(arg) # Revealed type is "None"defnew_types(arg: Union[Int, Float, None]) ->None:
ifisinstance(arg, int):
reveal_type(arg) # Revealed type is "__main__.Int"elifisinstance(arg, float):
reveal_type(arg) # Revealed type is "Union[__main__.Int, __main__.Float]" (NARROWING FAILED)else:
reveal_type(arg) # Revealed type is "None"defnew_types_not_optional(arg: Union[Int, Float]) ->None:
ifisinstance(arg, int):
reveal_type(arg) # Revealed type is "__main__.Int"elifisinstance(arg, float):
reveal_type(arg) # Revealed type is "__main__.Float"else:
reveal_type(arg)
The bug is fairly straightforward. When narrowing a Union of NewType types with isinstance, the narrowing fails if one of the possible types of the variable is None.
It is not just about Optional. Any extra type reveals narrowing issue:
defnew_types(arg: Union[Int, Float, str]) ->None:
ifisinstance(arg, int):
reveal_type(arg) # Revealed type is "__main__.Int"elifisinstance(arg, float):
reveal_type(arg) # Revealed type is "Union[__main__.Int, __main__.Float]" (NARROWING FAILED)else:
reveal_type(arg) # Revealed type is "builtins.str"
Activity
sobolevn commentedon Jan 15, 2022
It is not just about
Optional. Any extra type reveals narrowing issue:sobolevn commentedon Jan 15, 2022
This happens because
Intis treated as a subtype offloathere:mypy/mypy/meet.py
Line 530 in 17850b3
I don't think that this is correct 🤔
sobolevn commentedon Jan 15, 2022
Funny enough, this does type-check:
erictraut commentedon Aug 12, 2023
This bug appears to have been fixed. The latest version of mypy (1.5) does not exhibit the incorrect behavior indicated in the bug report.
hauntsaninja commentedon Aug 13, 2023
Fixed in #13781