Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add type inference for dict.keys membership #13372

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -6329,6 +6329,8 @@ def builtin_item_type(tp: Type) -> Type | None:
"builtins.dict",
"builtins.set",
"builtins.frozenset",
"_collections_abc.dict_keys",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about typing.KeysView? https://github.com/python/cpython/blob/70fc9641b56144854777aef29c145cd10789e3df/Lib/typing.py#L2701

And collections.abc.KeysView?
What about ValuesView and ItemsView?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And dict_values as well as dict_items 🙂

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about typing.KeysView?

Sounds good. I wasn't sure exactly what would be best to be included in this changeset. Let me drag all of those in too

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"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
Original file line number Diff line number Diff line change
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]"