Skip to content

Commit 507fc5c

Browse files
Add type inference for dict.keys membership (#13372)
Closes #13360
1 parent ec6d9d9 commit 507fc5c

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

mypy/checker.py

+2
Original file line numberDiff line numberDiff line change
@@ -6656,6 +6656,8 @@ def builtin_item_type(tp: Type) -> Type | None:
66566656
"builtins.dict",
66576657
"builtins.set",
66586658
"builtins.frozenset",
6659+
"_collections_abc.dict_keys",
6660+
"typing.KeysView",
66596661
]:
66606662
if not tp.args:
66616663
# TODO: fix tuple in lib-stub/builtins.pyi (it should be generic).

test-data/unit/pythoneval.test

+24
Original file line numberDiff line numberDiff line change
@@ -1636,3 +1636,27 @@ foo("")
16361636
foo(list(""))
16371637
foo(list((list(""), "")))
16381638
[out]
1639+
1640+
[case testNarrowTypeForDictKeys]
1641+
# flags: --strict-optional
1642+
from typing import Dict, KeysView, Optional
1643+
1644+
d: Dict[str, int]
1645+
key: Optional[str]
1646+
if key in d.keys():
1647+
reveal_type(key)
1648+
else:
1649+
reveal_type(key)
1650+
1651+
kv: KeysView[str]
1652+
k: Optional[str]
1653+
if k in kv:
1654+
reveal_type(k)
1655+
else:
1656+
reveal_type(k)
1657+
1658+
[out]
1659+
_testNarrowTypeForDictKeys.py:7: note: Revealed type is "builtins.str"
1660+
_testNarrowTypeForDictKeys.py:9: note: Revealed type is "Union[builtins.str, None]"
1661+
_testNarrowTypeForDictKeys.py:14: note: Revealed type is "builtins.str"
1662+
_testNarrowTypeForDictKeys.py:16: note: Revealed type is "Union[builtins.str, None]"

0 commit comments

Comments
 (0)