Skip to content

Commit bc65724

Browse files
committed
Add guard against too many literal values
1 parent d14b697 commit bc65724

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
@@ -212,6 +212,10 @@
212212
# see https://github.com/python/mypy/pull/5255#discussion_r196896335 for discussion.
213213
MAX_UNIONS: Final = 5
214214

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

216220
# Types considered safe for comparisons with --strict-equality due to known behaviour of __eq__.
217221
# NOTE: All these types are subtypes of AbstractSet.
@@ -3635,6 +3639,8 @@ def literal_expression_addition(
36353639
)
36363640
if len(values) == 1:
36373641
return LiteralType(values[0], self.named_type(lvalue[1]))
3642+
elif len(values) > MAX_LITERAL_ADDITION_VALUES:
3643+
return None
36383644
return make_simplified_union(
36393645
[LiteralType(val, self.named_type(lvalue[1])) for val in values]
36403646
)

test-data/unit/check-literal.test

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

30903090
[builtins fixtures/dict.pyi]
30913091
[typing fixtures/typing-typeddict.pyi]
3092+
3093+
[case testLiteralAdditionGuardMaxValues]
3094+
from typing_extensions import Literal
3095+
3096+
HexDigit = Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
3097+
3098+
def foo(a: HexDigit, b: HexDigit, c: HexDigit) -> None:
3099+
reveal_type(a + b + c) # N: Revealed type is "builtins.str"
3100+
[builtins fixtures/primitives.pyi]

0 commit comments

Comments
 (0)