Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
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 2 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 24 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]"
Morty Proxy This is a proxified and sanitized view of the page, visit original site.