Skip to content

Commit ec04655

Browse files
committed
Add test for Literal and enum incompatibility
See https://discuss.python.org/t/amend-pep-586-to-make-enum-values-subtypes-of-literal/59456 See python#19616 and python#19617 This test cases ensures if we make changes here we consciously think about this potential unsoundness
1 parent b060c2d commit ec04655

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

test-data/unit/check-literal.test

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3107,3 +3107,43 @@ def check(obj: A[Literal[1]]) -> None:
31073107
reveal_type(g('', obj)) # E: Cannot infer value of type parameter "T" of "g" \
31083108
# N: Revealed type is "Any"
31093109
[builtins fixtures/tuple.pyi]
3110+
3111+
[case testEnumLiteralIsNotIntLiteral]
3112+
# See https://discuss.python.org/t/amend-pep-586-to-make-enum-values-subtypes-of-literal/59456/4
3113+
from enum import IntEnum
3114+
from typing import Literal
3115+
3116+
class X(IntEnum):
3117+
a = 1
3118+
3119+
def __add__(self, value: int, /) -> int:
3120+
return self.value + value + 42
3121+
3122+
def __eq__(self, other: object):
3123+
return False
3124+
3125+
def __bool__(self) -> bool:
3126+
return False
3127+
3128+
def f(x: Literal[1]):
3129+
# 44 at runtime if you were to allow passing X.a
3130+
reveal_type(x + 1) # N: Revealed type is "builtins.int"
3131+
3132+
def g(x: Literal[1, 2]):
3133+
# false if you were to allow passing X.a
3134+
if x == 1:
3135+
reveal_type(x) # N: Revealed type is "Literal[1]"
3136+
else:
3137+
reveal_type(x) # N: Revealed type is "Literal[2]"
3138+
3139+
def h(x: Literal[0, 1]):
3140+
# false if you were to allow passing X.a
3141+
if x:
3142+
reveal_type(x) # N: Revealed type is "Literal[1]"
3143+
else:
3144+
reveal_type(x) # N: Revealed type is "Literal[0]"
3145+
3146+
f(X.a) # E: Argument 1 to "f" has incompatible type "Literal[X.a]"; expected "Literal[1]"
3147+
g(X.a) # E: Argument 1 to "g" has incompatible type "Literal[X.a]"; expected "Literal[1, 2]"
3148+
h(X.a) # E: Argument 1 to "h" has incompatible type "Literal[X.a]"; expected "Literal[0, 1]"
3149+
[builtins fixtures/primitives.pyi]

0 commit comments

Comments
 (0)