Skip to content

Commit

Permalink
Add type inference for dict.keys membership (#13372)
Browse files Browse the repository at this point in the history
Closes #13360
  • Loading branch information
matthewhughes934 committed Oct 27, 2022
1 parent ec6d9d9 commit 507fc5c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
2 changes: 2 additions & 0 deletions mypy/checker.py
Expand Up @@ -6656,6 +6656,8 @@ def builtin_item_type(tp: Type) -> Type | None:
"builtins.dict",
"builtins.set",
"builtins.frozenset",
"_collections_abc.dict_keys",
"typing.KeysView",
]:
if not tp.args:
# TODO: fix tuple in lib-stub/builtins.pyi (it should be generic).
Expand Down
24 changes: 24 additions & 0 deletions test-data/unit/pythoneval.test
Expand Up @@ -1636,3 +1636,27 @@ foo("")
foo(list(""))
foo(list((list(""), "")))
[out]

[case testNarrowTypeForDictKeys]
# flags: --strict-optional
from typing import Dict, KeysView, Optional

d: Dict[str, int]
key: Optional[str]
if key in d.keys():
reveal_type(key)
else:
reveal_type(key)

kv: KeysView[str]
k: Optional[str]
if k in kv:
reveal_type(k)
else:
reveal_type(k)

[out]
_testNarrowTypeForDictKeys.py:7: note: Revealed type is "builtins.str"
_testNarrowTypeForDictKeys.py:9: note: Revealed type is "Union[builtins.str, None]"
_testNarrowTypeForDictKeys.py:14: note: Revealed type is "builtins.str"
_testNarrowTypeForDictKeys.py:16: note: Revealed type is "Union[builtins.str, None]"

0 comments on commit 507fc5c

Please sign in to comment.