Skip to content

Fix narrowing down TypedDict unions with enum literal types #10415

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
May 4, 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
4 changes: 3 additions & 1 deletion mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2910,9 +2910,11 @@ def visit_index_with_type(self, left_type: Type, e: IndexExpr,

if isinstance(left_type, UnionType):
original_type = original_type or left_type
# Don't combine literal types, since we may need them for type narrowing.
return make_simplified_union([self.visit_index_with_type(typ, e,
original_type)
for typ in left_type.relevant_items()])
for typ in left_type.relevant_items()],
contract_literals=False)
elif isinstance(left_type, TupleType) and self.chk.in_checked_function():
# Special case for tuples. They return a more specific type when
# indexed by an integer literal.
Expand Down
23 changes: 23 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -1029,3 +1029,26 @@ else:
reveal_type(str_or_bool_literal) # N: Revealed type is "Union[Literal[False], Literal[True]]"

[builtins fixtures/primitives.pyi]

[case testNarrowingTypedDictUsingEnumLiteral]
from typing import Union
from typing_extensions import TypedDict, Literal
from enum import Enum

class E(Enum):
FOO = "a"
BAR = "b"

class Foo(TypedDict):
tag: Literal[E.FOO]
x: int

class Bar(TypedDict):
tag: Literal[E.BAR]
y: int

def f(d: Union[Foo, Bar]) -> None:
assert d['tag'] == E.FOO
d['x']
reveal_type(d) # N: Revealed type is "TypedDict('__main__.Foo', {'tag': Literal[__main__.E.FOO], 'x': builtins.int})"
[builtins fixtures/dict.pyi]