Skip to content

Fix narrowing of nested union of TypedDicts #11204

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

Merged
merged 1 commit into from
Oct 1, 2021
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
3 changes: 1 addition & 2 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -4676,8 +4676,7 @@ def replay_lookup(new_parent_type: ProperType) -> Optional[Type]:
# Take each element in the parent union and replay the original lookup procedure
# to figure out which parents are compatible.
new_parent_types = []
for item in parent_type.items:
item = get_proper_type(item)
for item in union_items(parent_type):
member_type = replay_lookup(item)
if member_type is None:
# We were unable to obtain the member type. So, we give up on refining this
Expand Down
29 changes: 29 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -1093,3 +1093,32 @@ def f(t: Type[T], a: A, b: B) -> None:
reveal_type(b) # N: Revealed type is "<nothing>"
else:
reveal_type(b) # N: Revealed type is "__main__.B"

[case testNarrowingNestedUnionOfTypedDicts]
from typing import Union
from typing_extensions import Literal, TypedDict

class A(TypedDict):
tag: Literal["A"]
a: int

class B(TypedDict):
tag: Literal["B"]
b: int

class C(TypedDict):
tag: Literal["C"]
c: int

AB = Union[A, B]
ABC = Union[AB, C]
abc: ABC

if abc["tag"] == "A":
reveal_type(abc) # N: Revealed type is "TypedDict('__main__.A', {'tag': Literal['A'], 'a': builtins.int})"
elif abc["tag"] == "C":
reveal_type(abc) # N: Revealed type is "TypedDict('__main__.C', {'tag': Literal['C'], 'c': builtins.int})"
else:
reveal_type(abc) # N: Revealed type is "TypedDict('__main__.B', {'tag': Literal['B'], 'b': builtins.int})"

[builtins fixtures/primitives.pyi]