Skip to content
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]