A an if statement like if x in some_dict.keys() doesn't narrow the type of x to the type of the key of some_dict.
This is in contrast with if x in some_dict which does correctly narrow.
(I had a search and didn't find a similar existing discussion, apologies if this isn't the case)
mypy correctly narrows the type in each of the if statements and the script passes.
Actual Behavior
mypy reports failures as:
script.py:7: error: Incompatible return value type (got "Optional[str]", expected "str")
script.py:15: error: Incompatible return value type (got "Optional[str]", expected "str")
Found 2 errors in 1 file (checked 1 source file)
Your Environment
Mypy version used: 0.971 and mypy 0.980+dev.e69bd9a7270daac8db409e8d08400d9d32367c32 (compiled: no) (current master)
Activity
sobolevn commented on Aug 9, 2022
We know that dict.keys() is safe! Please, feel free to send a PR.
Add type inference for `dict.keys` membership
Add type inference for `dict.keys` membership
Add type inference for `dict.keys` membership