Skip to content

Commit 24e2f21

Browse files
committed
Add guard against too many literal values
1 parent 36f5e2e commit 24e2f21

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

mypy/checkexpr.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,10 @@
207207
# see https://github.com/python/mypy/pull/5255#discussion_r196896335 for discussion.
208208
MAX_UNIONS: Final = 5
209209

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

211215
# Types considered safe for comparisons with --strict-equality due to known behaviour of __eq__.
212216
# NOTE: All these types are subtypes of AbstractSet.
@@ -3566,6 +3570,8 @@ def literal_expression_addition(
35663570
)
35673571
if len(values) == 1:
35683572
return LiteralType(values[0], self.named_type(lvalue[1]))
3573+
elif len(values) > MAX_LITERAL_ADDITION_VALUES:
3574+
return None
35693575
return make_simplified_union(
35703576
[LiteralType(val, self.named_type(lvalue[1])) for val in values]
35713577
)

test-data/unit/check-literal.test

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3097,3 +3097,12 @@ def func(d: LookupDict, pos: Literal["top_", "bottom_", ""]) -> str:
30973097

30983098
[builtins fixtures/dict.pyi]
30993099
[typing fixtures/typing-typeddict.pyi]
3100+
3101+
[case testLiteralAdditionGuardMaxValues]
3102+
from typing_extensions import Literal
3103+
3104+
HexDigit = Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
3105+
3106+
def foo(a: HexDigit, b: HexDigit, c: HexDigit) -> None:
3107+
reveal_type(a + b + c) # N: Revealed type is "builtins.str"
3108+
[builtins fixtures/primitives.pyi]

0 commit comments

Comments
 (0)