Skip to content

Fix ternary union for literals #18023

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 24, 2024
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
6 changes: 6 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -5805,6 +5805,12 @@ def visit_conditional_expr(self, e: ConditionalExpr, allow_none_return: bool = F
context=if_type_fallback,
allow_none_return=allow_none_return,
)

# In most cases using if_type as a context for right branch gives better inferred types.
# This is however not the case for literal types, so use the full context instead.
if is_literal_type_like(full_context_else_type) and not is_literal_type_like(else_type):
else_type = full_context_else_type

res: Type = make_simplified_union([if_type, else_type])
if has_uninhabited_component(res) and not isinstance(
get_proper_type(self.type_context[-1]), UnionType
Expand Down
24 changes: 24 additions & 0 deletions test-data/unit/check-literal.test
Original file line number Diff line number Diff line change
Expand Up @@ -2960,3 +2960,27 @@ class C(B[Literal["word"]]):
reveal_type(C().collection) # N: Revealed type is "builtins.list[Literal['word']]"
reveal_type(C().word) # N: Revealed type is "Literal['word']"
[builtins fixtures/tuple.pyi]

[case testLiteralTernaryUnionNarrowing]
from typing_extensions import Literal
from typing import Optional

SEP = Literal["a", "b"]

class Base:
def feed_data(
self,
sep: SEP,
) -> int:
return 0

class C(Base):
def feed_data(
self,
sep: Optional[SEP] = None,
) -> int:
if sep is None:
sep = "a" if int() else "b"
reveal_type(sep) # N: Revealed type is "Union[Literal['a'], Literal['b']]"
return super().feed_data(sep)
[builtins fixtures/tuple.pyi]
Loading