-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Description
Narrowing techniques perform very well when the condition is calculated inside the if condition. When these are made outside, I can understand that mypy cannot guarantee that the narrow will be ok as the boolean value of the condition might be changed before reaching the if statement. However, when the value of this condition is given outside of the if statement but defined as a Final
type, the narrow should be working
Minimal code to repdroduce it:
from typing import Optional, Final
def example_func(value: Optional[int] = None):
condition: Final = value is not None
if condition:
reveal_type(value) # Revealed type is "Union[builtins.int, None]"
value = value + 1 # MYPY ERROR
if value is not None:
reveal_type(value) # Revealed type is "builtins.int"
value = value + 1 # MYPY OK
return 0
Expected Behavior
The type of value
for the first if statement should be builtins.int
, as the condition
variable should remain with the same value that was previously assigned to it.
Actual Behavior
Narrowed not performed, and thus the type of value
is still inferred as Optional[int]
Your Environment
- Mypy version used: 0.931
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini
(and other config files): None - Python version used: Python 3.8.10
- Operating system and version: Ubuntu 20