8000 Add support for literal addition by cdce8p · Pull Request #18004 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Add support for literal addition #18004

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

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Add guard against too many literal values
  • Loading branch information
cdce8p committed May 19, 2025
commit bc657245acb54653b56e333dc0d38cf79ad5591e
6 changes: 6 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,10 @@
# see https://github.com/python/mypy/pull/5255#discussion_r196896335 for discussion.
MAX_UNIONS: Final = 5

# Use fallback type if literal addition of unions results in too many literal
# values. Explicitly set on the safe side to prevent accidental issues.
MAX_LITERAL_ADDITION_VALUES: Final = 15


# Types considered safe for comparisons with --strict-equality due to known behaviour of __eq__.
# NOTE: All these types are subtypes of AbstractSet.
Expand Down Expand Up @@ -3635,6 +3639,8 @@ def literal_expression_addition(
)
if len(values) == 1:
return LiteralType(values[0], self.named_type(lvalue[1]))
elif len(values) > MAX_LITERAL_ADDITION_VALUES:
return None
return make_simplified_union(
[LiteralType(val, self.named_type(lvalue[1])) for val in values]
)
Expand Down
9 changes: 9 additions & 0 deletions test-data/unit/check-literal.test
Original file line number Diff line number Diff line change
Expand Up @@ -3089,3 +3089,12 @@ def func(d: LookupDict, pos: Literal["top_", "bottom_", ""]) -> str:

[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testLiteralAdditionGuardMaxValues]
from typing_extensions import Literal

HexDigit = Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]

def foo(a: HexDigit, b: HexDigit, c: HexDigit) -> None:
reveal_type(a + b + c) # N: Revealed type is "builtins.str"
[builtins fixtures/primitives.pyi]
0