Debian Codegraph @

test-data/unit/check-enum.test

raw
1 -- This test file checks Enum
2
3 [case testEnumBasics]
4 from enum import Enum
5 class Medal(Enum):
6 gold = 1
7 silver = 2
8 bronze = 3
9 reveal_type(Medal.bronze) # N: Revealed type is "Literal[__main__.Medal.bronze]?"
10 m = Medal.gold
11 if int():
12 m = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "Medal")
13
14 [builtins fixtures/enum.pyi]
15
16 -- Creation from Enum call
17 -- -----------------------
18
19 [case testEnumCreatedFromStringLiteral]
20 from enum import Enum
21 from typing import Literal
22
23 x: Literal['ANT BEE CAT DOG'] = 'ANT BEE CAT DOG'
24 Animal = Enum('Animal', x)
25 reveal_type(Animal.ANT) # N: Revealed type is "Literal[__main__.Animal.ANT]?"
26 reveal_type(Animal.BEE) # N: Revealed type is "Literal[__main__.Animal.BEE]?"
27 reveal_type(Animal.CAT) # N: Revealed type is "Literal[__main__.Animal.CAT]?"
28 reveal_type(Animal.DOG) # N: Revealed type is "Literal[__main__.Animal.DOG]?"
29
30 [builtins fixtures/tuple.pyi]
31
32 [case testEnumCreatedFromFinalValue]
33 from enum import Enum
34 from typing import Final
35
36 x: Final['str'] = 'ANT BEE CAT DOG'
37 Animal = Enum('Animal', x)
38 reveal_type(Animal.ANT) # N: Revealed type is "Literal[__main__.Animal.ANT]?"
39 reveal_type(Animal.BEE) # N: Revealed type is "Literal[__main__.Animal.BEE]?"
40 reveal_type(Animal.CAT) # N: Revealed type is "Literal[__main__.Animal.CAT]?"
41 reveal_type(Animal.DOG) # N: Revealed type is "Literal[__main__.Animal.DOG]?"
42
43 [builtins fixtures/tuple.pyi]
44
45 -- Creation from EnumMeta
46 -- ----------------------
47
48 [case testEnumFromEnumMetaBasics]
49 from enum import EnumMeta
50 class Medal(metaclass=EnumMeta):
51 gold = 1
52 silver = "hello"
53 bronze = None
54 # Without __init__ the definition fails at runtime, but we want to verify that mypy
55 # uses `enum.EnumMeta` and not `enum.Enum` as the definition of what is enum.
56 def __init__(self, *args): pass
57 reveal_type(Medal.bronze) # N: Revealed type is "Literal[__main__.Medal.bronze]?"
58 m = Medal.gold
59 if int():
60 m = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "Medal")
61 [builtins fixtures/tuple.pyi]
62
63 [case testEnumFromEnumMetaSubclass]
64 from enum import EnumMeta
65 class Achievement(metaclass=EnumMeta): pass
66 class Medal(Achievement):
67 gold = 1
68 silver = "hello"
69 bronze = None
70 # See comment in testEnumFromEnumMetaBasics
71 def __init__(self, *args): pass
72 reveal_type(Medal.bronze) # N: Revealed type is "Literal[__main__.Medal.bronze]?"
73 m = Medal.gold
74 if int():
75 m = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "Medal")
76 [builtins fixtures/tuple.pyi]
77
78 [case testEnumFromEnumMetaGeneric]
79 from enum import EnumMeta
80 from typing import Generic, TypeVar
81 T = TypeVar("T")
82 class Medal(Generic[T], metaclass=EnumMeta): # E: Enum class cannot be generic
83 q = None
84 [builtins fixtures/enum.pyi]
85
86 [case testEnumNameAndValue]
87 from enum import Enum
88 class Truth(Enum):
89 true = True
90 false = False
91 x = ''
92 x = Truth.true.name
93 reveal_type(Truth.true.name) # N: Revealed type is "Literal['true']?"
94 reveal_type(Truth.false.value) # N: Revealed type is "Literal[False]?"
95 [builtins fixtures/bool.pyi]
96
97 [case testEnumValueExtended]
98 from enum import Enum
99 class Truth(Enum):
100 true = True
101 false = False
102
103 def infer_truth(truth: Truth) -> None:
104 reveal_type(truth.value) # N: Revealed type is "Literal[True]? | Literal[False]?"
105 [builtins fixtures/bool.pyi]
106
107 [case testEnumValueAllAuto]
108 from enum import Enum, auto
109 class Truth(Enum):
110 true = auto()
111 false = auto()
112
113 def infer_truth(truth: Truth) -> None:
114 reveal_type(truth.value) # N: Revealed type is "builtins.int"
115 [builtins fixtures/primitives.pyi]
116
117 [case testEnumValueSomeAuto]
118 from enum import Enum, auto
119 class Truth(Enum):
120 true = 8675309
121 false = auto()
122
123 def infer_truth(truth: Truth) -> None:
124 reveal_type(truth.value) # N: Revealed type is "builtins.int"
125 [builtins fixtures/primitives.pyi]
126
127 [case testEnumValueExtraMethods]
128 from enum import Enum
129 class Truth(Enum):
130 true = True
131 false = False
132
133 def foo(self) -> str:
134 return 'bar'
135
136 def infer_truth(truth: Truth) -> None:
137 reveal_type(truth.value) # N: Revealed type is "Literal[True]? | Literal[False]?"
138 [builtins fixtures/bool.pyi]
139
140 [case testEnumValueCustomAuto]
141 from enum import Enum, auto
142 class AutoName(Enum):
143
144 # In `typeshed`, this is a staticmethod and has more arguments,
145 # but I have lied a bit to keep the test stubs lean.
146 def _generate_next_value_(self) -> str:
147 return "name"
148
149 class Truth(AutoName):
150 true = auto()
151 false = auto()
152
153 def infer_truth(truth: Truth) -> None:
154 reveal_type(truth.value) # N: Revealed type is "builtins.str"
155 [builtins fixtures/primitives.pyi]
156
157 [case testEnumValueInhomogeneous]
158 from enum import Enum
159 class Truth(Enum):
160 true = 'True'
161 false = 0
162
163 def cannot_infer_truth(truth: Truth) -> None:
164 reveal_type(truth.value) # N: Revealed type is "Any"
165 [builtins fixtures/bool.pyi]
166
167 [case testEnumValueSameType]
168 from enum import Enum
169
170 def newbool() -> bool:
171 ...
172
173 class Truth(Enum):
174 true = newbool()
175 false = newbool()
176
177 def infer_truth(truth: Truth) -> None:
178 reveal_type(truth.value) # N: Revealed type is "builtins.bool"
179 [builtins fixtures/bool.pyi]
180
181 [case testEnumTruthyness]
182 # mypy: warn-unreachable
183 import enum
184 from typing import Literal
185
186 class E(enum.Enum):
187 zero = 0
188 one = 1
189
190 def print(s: str) -> None: ...
191
192 if E.zero:
193 print("zero is true")
194 if not E.zero:
195 print("zero is false") # E: Statement is unreachable
196
197 if E.one:
198 print("one is true")
199 if not E.one:
200 print("one is false") # E: Statement is unreachable
201
202 def main(zero: Literal[E.zero], one: Literal[E.one]) -> None:
203 if zero:
204 print("zero is true")
205 if not zero:
206 print("zero is false") # E: Statement is unreachable
207 if one:
208 print("one is true")
209 if not one:
210 print("one is false") # E: Statement is unreachable
211 [builtins fixtures/tuple.pyi]
212
213 [case testEnumTruthynessCustomDunderBool]
214 # mypy: warn-unreachable
215 import enum
216 from typing import Literal
217
218 class E(enum.Enum):
219 zero = 0
220 one = 1
221 def __bool__(self) -> Literal[False]:
222 return False
223
224 def print(s: str) -> None: ...
225
226 if E.zero:
227 print("zero is true") # E: Statement is unreachable
228 if not E.zero:
229 print("zero is false")
230
231 if E.one:
232 print("one is true") # E: Statement is unreachable
233 if not E.one:
234 print("one is false")
235
236 def main(zero: Literal[E.zero], one: Literal[E.one]) -> None:
237 if zero:
238 print("zero is true") # E: Statement is unreachable
239 if not zero:
240 print("zero is false")
241 if one:
242 print("one is true") # E: Statement is unreachable
243 if not one:
244 print("one is false")
245 [builtins fixtures/enum.pyi]
246
247 [case testEnumTruthynessStrEnum]
248 # mypy: warn-unreachable
249 import enum
250 from typing import Literal
251
252 class E(enum.StrEnum):
253 empty = ""
254 not_empty = "asdf"
255
256 def print(s: str) -> None: ...
257
258 if E.empty:
259 print("empty is true")
260 if not E.empty:
261 print("empty is false")
262
263 if E.not_empty:
264 print("not_empty is true")
265 if not E.not_empty:
266 print("not_empty is false")
267
268 def main(empty: Literal[E.empty], not_empty: Literal[E.not_empty]) -> None:
269 if empty:
270 print("empty is true")
271 if not empty:
272 print("empty is false")
273 if not_empty:
274 print("not_empty is true")
275 if not not_empty:
276 print("not_empty is false")
277 [builtins fixtures/enum.pyi]
278
279 [case testEnumUnique]
280 import enum
281 @enum.unique
282 class E(enum.Enum):
283 x = 1
284 y = 1 # NOTE: This duplicate value is not detected by mypy at the moment
285 x = 1
286 x = E.x
287 [builtins fixtures/enum.pyi]
288 [out]
289 main:7: error: Incompatible types in assignment (expression has type "E", variable has type "int")
290
291 [case testIntEnum_assignToIntVariable]
292 from enum import IntEnum
293 class N(IntEnum):
294 x = 1
295 y = 1
296 n = 1
297 if int():
298 n = N.x # Subclass of int, so it's okay
299 s = ''
300 if int():
301 s = N.y # E: Incompatible types in assignment (expression has type "N", variable has type "str")
302 [builtins fixtures/enum.pyi]
303
304 [case testIntEnum_functionTakingIntEnum]
305 from enum import IntEnum
306 class SomeIntEnum(IntEnum):
307 x = 1
308 def takes_some_int_enum(n: SomeIntEnum):
309 pass
310 takes_some_int_enum(SomeIntEnum.x)
311 takes_some_int_enum(1) # Error
312 takes_some_int_enum(SomeIntEnum(1)) # How to deal with the above
313 [builtins fixtures/enum.pyi]
314 [out]
315 main:7: error: Argument 1 to "takes_some_int_enum" has incompatible type "int"; expected "SomeIntEnum"
316
317 [case testIntEnum_functionTakingInt]
318 from enum import IntEnum
319 class SomeIntEnum(IntEnum):
320 x = 1
321 def takes_int(i: int):
322 pass
323 takes_int(SomeIntEnum.x)
324 takes_int(2)
325 [builtins fixtures/enum.pyi]
326
327 [case testIntEnum_functionReturningIntEnum]
328 from enum import IntEnum
329 class SomeIntEnum(IntEnum):
330 x = 1
331 def returns_some_int_enum() -> SomeIntEnum:
332 return SomeIntEnum.x
333 an_int = 1
334 an_int = returns_some_int_enum()
335
336 an_enum = SomeIntEnum.x
337 an_enum = returns_some_int_enum()
338 [builtins fixtures/enum.pyi]
339 [out]
340
341 [case testStrEnumCreation]
342 # flags: --python-version 3.11
343 from enum import StrEnum
344
345 class MyStrEnum(StrEnum):
346 x = 'x'
347 y = 'y'
348
349 reveal_type(MyStrEnum.x) # N: Revealed type is "Literal[__main__.MyStrEnum.x]?"
350 reveal_type(MyStrEnum.x.value) # N: Revealed type is "Literal['x']?"
351 reveal_type(MyStrEnum.y) # N: Revealed type is "Literal[__main__.MyStrEnum.y]?"
352 reveal_type(MyStrEnum.y.value) # N: Revealed type is "Literal['y']?"
353 [builtins fixtures/enum.pyi]
354 [out]
355
356 [case testEnumMethods]
357 from enum import Enum
358
359 class Color(Enum):
360 red = 1
361 green = 2
362
363 def m(self, x: int): pass
364 @staticmethod
365 def m2(x: int): pass
366
367 Color.red.m('')
368 Color.m2('')
369 [builtins fixtures/staticmethod.pyi]
370 [out]
371 main:11: error: Argument 1 to "m" of "Color" has incompatible type "str"; expected "int"
372 main:12: error: Argument 1 to "m2" of "Color" has incompatible type "str"; expected "int"
373
374 [case testIntEnum_ExtendedIntEnum_functionTakingExtendedIntEnum]
375 from enum import IntEnum
376 class ExtendedIntEnum(IntEnum):
377 pass
378 class SomeExtIntEnum(ExtendedIntEnum):
379 x = 1
380
381 def takes_int(i: int):
382 pass
383 takes_int(SomeExtIntEnum.x)
384
385 def takes_some_ext_int_enum(s: SomeExtIntEnum):
386 pass
387 takes_some_ext_int_enum(SomeExtIntEnum.x)
388 [builtins fixtures/enum.pyi]
389
390 [case testNamedTupleEnum]
391 from typing import NamedTuple
392 from enum import Enum
393
394 N = NamedTuple('N', [('bar', int)])
395
396 class E(N, Enum):
397 X = N(1)
398
399 def f(x: E) -> None: pass
400
401 f(E.X)
402 [builtins fixtures/tuple.pyi]
403
404 [case testEnumCall]
405 from enum import IntEnum
406 class E(IntEnum):
407 a = 1
408 x: int
409 reveal_type(E(x))
410 [builtins fixtures/tuple.pyi]
411 [out]
412 main:5: note: Revealed type is "__main__.E"
413
414 [case testEnumIndex]
415 from enum import IntEnum
416 class E(IntEnum):
417 a = 1
418 s: str
419 reveal_type(E[s])
420 [builtins fixtures/enum.pyi]
421 [out]
422 main:5: note: Revealed type is "__main__.E"
423
424 [case testEnumIndexError]
425 from enum import IntEnum
426 class E(IntEnum):
427 a = 1
428 E[1] # E: Enum index should be a string (actual index type "int")
429 x = E[1] # E: Enum index should be a string (actual index type "int")
430 [builtins fixtures/enum.pyi]
431
432 [case testEnumIndexIsNotAnAlias]
433 from enum import Enum
434
435 class E(Enum):
436 a = 1
437 b = 2
438 reveal_type(E['a']) # N: Revealed type is "__main__.E"
439 E['a']
440 x = E['a']
441 reveal_type(x) # N: Revealed type is "__main__.E"
442
443 def get_member(name: str) -> E:
444 val = E[name]
445 return val
446
447 reveal_type(get_member('a')) # N: Revealed type is "__main__.E"
448 [builtins fixtures/enum.pyi]
449
450 [case testGenericEnum]
451 from enum import Enum
452 from typing import Generic, TypeVar
453
454 T = TypeVar('T')
455
456 class F(Generic[T], Enum): # E: Enum class cannot be generic
457 x: T
458 y: T
459
460 reveal_type(F[int].x) # E: Access to generic instance variables via class is ambiguous \
461 # N: Revealed type is "builtins.int"
462 [builtins fixtures/enum.pyi]
463
464 [case testEnumFlag]
465 from enum import Flag
466 class C(Flag):
467 a = 1
468 b = 2
469 x = C.a
470 if int():
471 x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "C")
472 if int():
473 x = x | C.b
474 [builtins fixtures/enum.pyi]
475
476 [case testEnumIntFlag]
477 from enum import IntFlag
478 class C(IntFlag):
479 a = 1
480 b = 2
481 x = C.a
482 if int():
483 x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "C")
484 if int():
485 x = x | C.b
486 [builtins fixtures/enum.pyi]
487
488 [case testAnonymousEnum]
489 from enum import Enum
490 class A:
491 def f(self) -> None:
492 class E(Enum):
493 a = 1
494 self.x = E.a
495 a = A()
496 reveal_type(a.x)
497 [builtins fixtures/enum.pyi]
498 [out]
499 main:8: note: Revealed type is "__main__.E@4"
500
501 [case testEnumInClassBody]
502 from enum import Enum
503 class A:
504 class E(Enum):
505 a = 1
506 class B:
507 class E(Enum):
508 a = 1
509 x = A.E.a
510 y = B.E.a
511 if int():
512 x = y # E: Incompatible types in assignment (expression has type "__main__.B.E", variable has type "__main__.A.E")
513 [builtins fixtures/enum.pyi]
514
515 [case testFunctionalEnumString]
516 from enum import Enum, IntEnum
517 E = Enum('E', 'foo bar')
518 I = IntEnum('I', ' bar, baz ')
519 reveal_type(E.foo)
520 reveal_type(E.bar.value)
521 reveal_type(I.bar)
522 reveal_type(I.baz.value)
523 [builtins fixtures/enum.pyi]
524 [out]
525 main:4: note: Revealed type is "Literal[__main__.E.foo]?"
526 main:5: note: Revealed type is "Any"
527 main:6: note: Revealed type is "Literal[__main__.I.bar]?"
528 main:7: note: Revealed type is "builtins.int"
529
530 [case testFunctionalEnumListOfStrings]
531 from enum import Enum, IntEnum
532 E = Enum('E', ('foo', 'bar'))
533 F = IntEnum('F', ['bar', 'baz'])
534 reveal_type(E.foo)
535 reveal_type(F.baz)
536 [builtins fixtures/enum.pyi]
537 [out]
538 main:4: note: Revealed type is "Literal[__main__.E.foo]?"
539 main:5: note: Revealed type is "Literal[__main__.F.baz]?"
540
541 [case testFunctionalEnumListOfPairs]
542 from enum import Enum, IntEnum
543 E = Enum('E', [('foo', 1), ['bar', 2]])
544 F = IntEnum('F', (['bar', 1], ('baz', 2)))
545 reveal_type(E.foo)
546 reveal_type(F.baz)
547 reveal_type(E.foo.value)
548 reveal_type(F.bar.name)
549 [builtins fixtures/enum.pyi]
550 [out]
551 main:4: note: Revealed type is "Literal[__main__.E.foo]?"
552 main:5: note: Revealed type is "Literal[__main__.F.baz]?"
553 main:6: note: Revealed type is "Literal[1]?"
554 main:7: note: Revealed type is "Literal['bar']?"
555
556 [case testFunctionalEnumDict]
557 from enum import Enum, IntEnum
558 E = Enum('E', {'foo': 1, 'bar': 2})
559 F = IntEnum('F', {'bar': 1, 'baz': 2})
560 reveal_type(E.foo)
561 reveal_type(F.baz)
562 reveal_type(E.foo.value)
563 reveal_type(F.bar.name)
564 [builtins fixtures/enum.pyi]
565 [out]
566 main:4: note: Revealed type is "Literal[__main__.E.foo]?"
567 main:5: note: Revealed type is "Literal[__main__.F.baz]?"
568 main:6: note: Revealed type is "Literal[1]?"
569 main:7: note: Revealed type is "Literal['bar']?"
570
571
572 [case testEnumKeywordsArgs]
573 from enum import Enum, IntEnum
574
575 PictureSize = Enum('PictureSize', 'P0 P1 P2 P3 P4 P5 P6 P7 P8', type=str, module=__name__)
576 fake_enum1 = Enum('fake_enum1', ['a', 'b'])
577 fake_enum2 = Enum('fake_enum2', names=['a', 'b'])
578 fake_enum3 = Enum(value='fake_enum3', names=['a', 'b'])
579 fake_enum4 = Enum(value='fake_enum4', names=['a', 'b'] , module=__name__)
580 [builtins fixtures/enum.pyi]
581
582 [case testFunctionalEnumErrors]
583 from enum import Enum, IntEnum
584 A = Enum('A') # E: Too few arguments for Enum()
585 B = Enum('B', 42) # E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members
586 C = Enum('C', 'a b', 'x', 'y', 'z', 'p', 'q') # E: Too many arguments for Enum()
587 D = Enum('D', foo) # E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members \
588 # E: Name "foo" is not defined
589 bar = 'x y z'
590 E = Enum('E', bar) # E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members
591 I = IntEnum('I') # E: Too few arguments for IntEnum()
592 J = IntEnum('I', 42) # E: Second argument of IntEnum() must be string, tuple, list or dict literal for mypy to determine Enum members
593 K = IntEnum('I', 'p q', 'x', 'y', 'z', 'p', 'q') # E: Too many arguments for IntEnum()
594 L = Enum('L', ' ') # E: Enum() needs at least one item
595 M = Enum('M', ()) # E: Enum() needs at least one item
596 N = IntEnum('M', []) # E: IntEnum() needs at least one item
597 P = Enum('P', [42]) # E: Enum() with tuple or list expects strings or (name, value) pairs
598 Q = Enum('Q', [('a', 42, 0)]) # E: Enum() with tuple or list expects strings or (name, value) pairs
599 R = IntEnum('R', [[0, 42]]) # E: IntEnum() with tuple or list expects strings or (name, value) pairs
600 S = Enum('S', {1: 1}) # E: Enum() with dict literal requires string literals
601 T = Enum('T', keyword='a b') # E: Unexpected keyword argument "keyword"
602 U = Enum('U', *['a']) # E: Unexpected arguments to Enum()
603 V = Enum('U', **{'a': 1}) # E: Unexpected arguments to Enum()
604 W = Enum('W', 'a b')
605 W.c # E: "type[W]" has no attribute "c"
606 X = Enum('Something', 'a b') # E: String argument 1 "Something" to enum.Enum(...) does not match variable name "X"
607 reveal_type(X.a) # N: Revealed type is "Literal[__main__.X.a]?"
608 X.asdf # E: "type[X]" has no attribute "asdf"
609
610
611 [builtins fixtures/tuple.pyi]
612 [typing fixtures/typing-medium.pyi]
613
614 [case testFunctionalEnumFlag]
615 from enum import Flag, IntFlag
616 A = Flag('A', 'x y')
617 B = IntFlag('B', 'a b')
618 reveal_type(A.x) # N: Revealed type is "Literal[__main__.A.x]?"
619 reveal_type(B.a) # N: Revealed type is "Literal[__main__.B.a]?"
620 reveal_type(A.x.name) # N: Revealed type is "Literal['x']?"
621 reveal_type(B.a.name) # N: Revealed type is "Literal['a']?"
622
623 reveal_type(A.x.value) # N: Revealed type is "builtins.int"
624 reveal_type(B.a.value) # N: Revealed type is "builtins.int"
625 [builtins fixtures/enum.pyi]
626
627 [case testAnonymousFunctionalEnum]
628 from enum import Enum
629 class A:
630 def f(self) -> None:
631 E = Enum('E', 'a b')
632 self.x = E.a
633 a = A()
634 reveal_type(a.x)
635 [builtins fixtures/enum.pyi]
636 [out]
637 main:7: note: Revealed type is "__main__.E@4"
638
639 [case testFunctionalEnumInClassBody]
640 from enum import Enum
641 class A:
642 E = Enum('E', 'a b')
643 class B:
644 E = Enum('E', 'a b')
645 x = A.E.a
646 y = B.E.a
647 if int():
648 x = y # E: Incompatible types in assignment (expression has type "__main__.B.E", variable has type "__main__.A.E")
649 [builtins fixtures/enum.pyi]
650
651 [case testFunctionalEnumProtocols]
652 from enum import IntEnum
653 Color = IntEnum('Color', 'red green blue')
654 reveal_type(Color['green']) # N: Revealed type is "__main__.Color"
655 for c in Color:
656 reveal_type(c) # N: Revealed type is "__main__.Color"
657 reveal_type(list(Color)) # N: Revealed type is "builtins.list[__main__.Color]"
658
659 [builtins fixtures/list.pyi]
660
661 [case testEnumWorkWithForward]
662 from enum import Enum
663 a: E = E.x # type: ignore[used-before-def]
664 class E(Enum):
665 x = 1
666 y = 2
667 [builtins fixtures/enum.pyi]
668 [out]
669
670 [case testEnumWorkWithForward2]
671 from enum import Enum
672 b: F
673 F = Enum('F', {'x': 1, 'y': 2})
674
675 def fn(x: F) -> None:
676 pass
677 fn(b)
678 [builtins fixtures/enum.pyi]
679 [out]
680
681 [case testFunctionalEnum]
682 # TODO: Needs to have enum34 stubs somehow
683 from enum import Enum
684 Eu = Enum(u'Eu', u'a b')
685 Eb = Enum(b'Eb', b'a b') # E: Enum() expects a string literal as the first argument
686 Gu = Enum(u'Gu', {u'a': 1})
687 Gb = Enum(b'Gb', {b'a': 1}) # E: Enum() expects a string literal as the first argument
688 Hu = Enum(u'Hu', [u'a'])
689 Hb = Enum(b'Hb', [b'a']) # E: Enum() expects a string literal as the first argument
690 Eu.a
691 Eb.a
692 Gu.a
693 Gb.a
694 Hu.a
695 Hb.a
696 [builtins fixtures/enum.pyi]
697 [out]
698
699 [case testEnumIncremental]
700 import m
701 reveal_type(m.E.a)
702 reveal_type(m.F.b)
703 [file m.py]
704 from enum import Enum
705 class E(Enum):
706 a = 1
707 b = 2
708 F = Enum('F', 'a b')
709 [builtins fixtures/enum.pyi]
710 [rechecked]
711 [stale]
712 [out1]
713 main:2: note: Revealed type is "Literal[m.E.a]?"
714 main:3: note: Revealed type is "Literal[m.F.b]?"
715 [out2]
716 main:2: note: Revealed type is "Literal[m.E.a]?"
717 main:3: note: Revealed type is "Literal[m.F.b]?"
718
719 [case testEnumAuto]
720 from enum import Enum, auto
721 class Test(Enum):
722 a = auto()
723 b = auto()
724
725 reveal_type(Test.a) # N: Revealed type is "Literal[__main__.Test.a]?"
726 [builtins fixtures/primitives.pyi]
727
728 [case testEnumAttributeAccessMatrix]
729 from enum import Enum, IntEnum, IntFlag, Flag, EnumMeta, auto
730 from typing import Literal
731
732 def is_x(val: Literal['x']) -> None: pass
733
734 A1 = Enum('A1', 'x')
735 class A2(Enum):
736 x = auto()
737 class A3(Enum):
738 x = 1
739
740 is_x(reveal_type(A1.x.name)) # N: Revealed type is "Literal['x']"
741 is_x(reveal_type(A1.x._name_)) # N: Revealed type is "Literal['x']"
742 reveal_type(A1.x.value) # N: Revealed type is "Any"
743 reveal_type(A1.x._value_) # N: Revealed type is "Any"
744 is_x(reveal_type(A2.x.name)) # N: Revealed type is "Literal['x']"
745 is_x(reveal_type(A2.x._name_)) # N: Revealed type is "Literal['x']"
746 reveal_type(A2.x.value) # N: Revealed type is "builtins.int"
747 reveal_type(A2.x._value_) # N: Revealed type is "builtins.int"
748 is_x(reveal_type(A3.x.name)) # N: Revealed type is "Literal['x']"
749 is_x(reveal_type(A3.x._name_)) # N: Revealed type is "Literal['x']"
750 reveal_type(A3.x.value) # N: Revealed type is "Literal[1]?"
751 reveal_type(A3.x._value_) # N: Revealed type is "Literal[1]?"
752
753 B1 = IntEnum('B1', 'x')
754 class B2(IntEnum):
755 x = auto()
756 class B3(IntEnum):
757 x = 1
758
759 is_x(reveal_type(B1.x.name)) # N: Revealed type is "Literal['x']"
760 is_x(reveal_type(B1.x._name_)) # N: Revealed type is "Literal['x']"
761 reveal_type(B1.x.value) # N: Revealed type is "builtins.int"
762 reveal_type(B1.x._value_) # N: Revealed type is "builtins.int"
763 is_x(reveal_type(B2.x.name)) # N: Revealed type is "Literal['x']"
764 is_x(reveal_type(B2.x._name_)) # N: Revealed type is "Literal['x']"
765 reveal_type(B2.x.value) # N: Revealed type is "builtins.int"
766 reveal_type(B2.x._value_) # N: Revealed type is "builtins.int"
767 is_x(reveal_type(B3.x.name)) # N: Revealed type is "Literal['x']"
768 is_x(reveal_type(B3.x._name_)) # N: Revealed type is "Literal['x']"
769 reveal_type(B3.x.value) # N: Revealed type is "Literal[1]?"
770 reveal_type(B3.x._value_) # N: Revealed type is "Literal[1]?"
771
772 C1 = IntFlag('C1', 'x')
773 class C2(IntFlag):
774 x = auto()
775 class C3(IntFlag):
776 x = 1
777
778 is_x(reveal_type(C1.x.name)) # N: Revealed type is "Literal['x']"
779 is_x(reveal_type(C1.x._name_)) # N: Revealed type is "Literal['x']"
780 reveal_type(C1.x.value) # N: Revealed type is "builtins.int"
781 reveal_type(C1.x._value_) # N: Revealed type is "builtins.int"
782 is_x(reveal_type(C2.x.name)) # N: Revealed type is "Literal['x']"
783 is_x(reveal_type(C2.x._name_)) # N: Revealed type is "Literal['x']"
784 reveal_type(C2.x.value) # N: Revealed type is "builtins.int"
785 reveal_type(C2.x._value_) # N: Revealed type is "builtins.int"
786 is_x(reveal_type(C3.x.name)) # N: Revealed type is "Literal['x']"
787 is_x(reveal_type(C3.x._name_)) # N: Revealed type is "Literal['x']"
788 reveal_type(C3.x.value) # N: Revealed type is "Literal[1]?"
789 reveal_type(C3.x._value_) # N: Revealed type is "Literal[1]?"
790
791 D1 = Flag('D1', 'x')
792 class D2(Flag):
793 x = auto()
794 class D3(Flag):
795 x = 1
796
797 is_x(reveal_type(D1.x.name)) # N: Revealed type is "Literal['x']"
798 is_x(reveal_type(D1.x._name_)) # N: Revealed type is "Literal['x']"
799 reveal_type(D1.x.value) # N: Revealed type is "builtins.int"
800 reveal_type(D1.x._value_) # N: Revealed type is "builtins.int"
801 is_x(reveal_type(D2.x.name)) # N: Revealed type is "Literal['x']"
802 is_x(reveal_type(D2.x._name_)) # N: Revealed type is "Literal['x']"
803 reveal_type(D2.x.value) # N: Revealed type is "builtins.int"
804 reveal_type(D2.x._value_) # N: Revealed type is "builtins.int"
805 is_x(reveal_type(D3.x.name)) # N: Revealed type is "Literal['x']"
806 is_x(reveal_type(D3.x._name_)) # N: Revealed type is "Literal['x']"
807 reveal_type(D3.x.value) # N: Revealed type is "Literal[1]?"
808 reveal_type(D3.x._value_) # N: Revealed type is "Literal[1]?"
809
810 # TODO: Generalize our enum functional API logic to work with subclasses of Enum
811 # See https://github.com/python/mypy/issues/6037
812
813 class Parent(Enum): pass
814 # E1 = Parent('E1', 'x') # See above TODO
815 class E2(Parent):
816 x = auto()
817 class E3(Parent):
818 x = 1
819
820 is_x(reveal_type(E2.x.name)) # N: Revealed type is "Literal['x']"
821 is_x(reveal_type(E2.x._name_)) # N: Revealed type is "Literal['x']"
822 reveal_type(E2.x.value) # N: Revealed type is "builtins.int"
823 reveal_type(E2.x._value_) # N: Revealed type is "builtins.int"
824 is_x(reveal_type(E3.x.name)) # N: Revealed type is "Literal['x']"
825 is_x(reveal_type(E3.x._name_)) # N: Revealed type is "Literal['x']"
826 reveal_type(E3.x.value) # N: Revealed type is "Literal[1]?"
827 reveal_type(E3.x._value_) # N: Revealed type is "Literal[1]?"
828
829
830 # TODO: Figure out if we can construct enums using EnumMetas using the functional API.
831 # Also figure out if we even care about supporting that use case.
832 class F2(metaclass=EnumMeta):
833 x = auto()
834 class F3(metaclass=EnumMeta):
835 x = 1
836
837 F2.x.name # E: "F2" has no attribute "name"
838 F2.x._name_ # E: "F2" has no attribute "_name_"
839 F2.x.value # E: "F2" has no attribute "value"
840 F2.x._value_ # E: "F2" has no attribute "_value_"
841 F3.x.name # E: "F3" has no attribute "name"
842 F3.x._name_ # E: "F3" has no attribute "_name_"
843 F3.x.value # E: "F3" has no attribute "value"
844 F3.x._value_ # E: "F3" has no attribute "_value_"
845 [builtins fixtures/primitives.pyi]
846
847 [case testEnumAttributeChangeIncremental]
848 from a import SomeEnum
849 reveal_type(SomeEnum.a.value)
850
851 [file a.py]
852 from b import SomeEnum
853
854 [file b.py]
855 from enum import Enum
856 class SomeEnum(Enum):
857 a = 1
858
859 [file b.py.2]
860 from enum import Enum
861 class SomeEnum(Enum):
862 a = "foo"
863 [builtins fixtures/enum.pyi]
864 [out]
865 main:2: note: Revealed type is "Literal[1]?"
866 [out2]
867 main:2: note: Revealed type is "Literal['foo']?"
868
869 [case testEnumReachabilityChecksBasic]
870 # flags: --warn-unreachable
871 from enum import Enum
872 from typing import Literal
873
874 class Foo(Enum):
875 A = 1
876 B = 2
877 C = 3
878
879 x: Literal[Foo.A, Foo.B, Foo.C]
880 if x is Foo.A:
881 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
882 elif x is Foo.B:
883 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
884 elif x is Foo.C:
885 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.C]"
886 else:
887 reveal_type(x) # E: Statement is unreachable
888 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A] | Literal[__main__.Foo.B] | Literal[__main__.Foo.C]"
889
890 if Foo.A is x:
891 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
892 elif Foo.B is x:
893 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
894 elif Foo.C is x:
895 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.C]"
896 else:
897 reveal_type(x) # E: Statement is unreachable
898 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A] | Literal[__main__.Foo.B] | Literal[__main__.Foo.C]"
899
900 y: Foo
901 if y is Foo.A:
902 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
903 elif y is Foo.B:
904 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
905 elif y is Foo.C:
906 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.C]"
907 else:
908 reveal_type(y) # E: Statement is unreachable
909 reveal_type(y) # N: Revealed type is "__main__.Foo"
910
911 if Foo.A is y:
912 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
913 elif Foo.B is y:
914 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
915 elif Foo.C is y:
916 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.C]"
917 else:
918 reveal_type(y) # E: Statement is unreachable
919 reveal_type(y) # N: Revealed type is "__main__.Foo"
920 [builtins fixtures/bool.pyi]
921
922 [case testEnumReachabilityChecksWithOrdering]
923 # flags: --warn-unreachable
924 from enum import Enum
925 from typing import Literal
926
927 class Foo(Enum):
928 _order_ = "A B"
929 A = 1
930 B = 2
931
932 Foo._order_ # E: "type[Foo]" has no attribute "_order_"
933
934 x: Literal[Foo.A, Foo.B]
935 if x is Foo.A:
936 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
937 elif x is Foo.B:
938 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
939 else:
940 reveal_type(x) # E: Statement is unreachable
941
942 class Bar(Enum):
943 __order__ = "A B"
944 A = 1
945 B = 2
946
947 Bar.__order__ # E: "type[Bar]" has no attribute "__order__"
948
949 y: Literal[Bar.A, Bar.B]
950 if y is Bar.A:
951 reveal_type(y) # N: Revealed type is "Literal[__main__.Bar.A]"
952 elif y is Bar.B:
953 reveal_type(y) # N: Revealed type is "Literal[__main__.Bar.B]"
954 else:
955 reveal_type(y) # E: Statement is unreachable
956
957 x2: Foo
958 if x2 is Foo.A:
959 reveal_type(x2) # N: Revealed type is "Literal[__main__.Foo.A]"
960 elif x2 is Foo.B:
961 reveal_type(x2) # N: Revealed type is "Literal[__main__.Foo.B]"
962 else:
963 reveal_type(x2) # E: Statement is unreachable
964
965 y2: Bar
966 if y2 is Bar.A:
967 reveal_type(y2) # N: Revealed type is "Literal[__main__.Bar.A]"
968 elif y2 is Bar.B:
969 reveal_type(y2) # N: Revealed type is "Literal[__main__.Bar.B]"
970 else:
971 reveal_type(y2) # E: Statement is unreachable
972 [builtins fixtures/tuple.pyi]
973
974 [case testEnumReachabilityChecksIndirect]
975 # flags: --warn-unreachable
976 from enum import Enum
977 from typing import Final, Literal
978
979 class Foo(Enum):
980 A = 1
981 B = 2
982 C = 3
983
984 def accepts_foo_a(x: Literal[Foo.A]) -> None: ...
985
986 x: Foo
987 y: Literal[Foo.A]
988 z: Final = Foo.A
989
990 if x is y:
991 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
992 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
993 else:
994 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B] | Literal[__main__.Foo.C]"
995 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
996 reveal_type(x) # N: Revealed type is "__main__.Foo"
997 if y is x:
998 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
999 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
1000 else:
1001 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B] | Literal[__main__.Foo.C]"
1002 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
1003 reveal_type(x) # N: Revealed type is "__main__.Foo"
1004
1005 if x is z:
1006 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
1007 reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
1008 accepts_foo_a(z)
1009 else:
1010 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B] | Literal[__main__.Foo.C]"
1011 reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
1012 accepts_foo_a(z)
1013 reveal_type(x) # N: Revealed type is "__main__.Foo"
1014 if z is x:
1015 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
1016 reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
1017 accepts_foo_a(z)
1018 else:
1019 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B] | Literal[__main__.Foo.C]"
1020 reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
1021 accepts_foo_a(z)
1022 reveal_type(x) # N: Revealed type is "__main__.Foo"
1023
1024 if y is z:
1025 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
1026 reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
1027 accepts_foo_a(z)
1028 else:
1029 reveal_type(y) # E: Statement is unreachable
1030 reveal_type(z)
1031 if z is y:
1032 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
1033 reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
1034 accepts_foo_a(z)
1035 else:
1036 reveal_type(y) # E: Statement is unreachable
1037 reveal_type(z)
1038 [builtins fixtures/bool.pyi]
1039
1040 [case testEnumReachabilityNarrowingForUnionMessiness]
1041 # flags: --warn-unreachable
1042 from enum import Enum
1043 from typing import Literal
1044
1045 class Foo(Enum):
1046 A = 1
1047 B = 2
1048 C = 3
1049
1050 x: Foo
1051 y: Literal[Foo.A, Foo.B]
1052 z: Literal[Foo.B, Foo.C]
1053
1054 if x is y:
1055 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A] | Literal[__main__.Foo.B]"
1056 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A] | Literal[__main__.Foo.B]"
1057 else:
1058 reveal_type(x) # N: Revealed type is "__main__.Foo"
1059 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A] | Literal[__main__.Foo.B]"
1060
1061 if y is z:
1062 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
1063 reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.B]"
1064 else:
1065 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A] | Literal[__main__.Foo.B]"
1066 reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.B] | Literal[__main__.Foo.C]"
1067 [builtins fixtures/bool.pyi]
1068
1069 [case testEnumReachabilityWithNone]
1070 # flags: --warn-unreachable
1071 from enum import Enum
1072 from typing import Optional
1073
1074 class Foo(Enum):
1075 A = 1
1076 B = 2
1077 C = 3
1078
1079 x: Optional[Foo]
1080 if x:
1081 reveal_type(x) # N: Revealed type is "__main__.Foo"
1082 else:
1083 reveal_type(x) # N: Revealed type is "None"
1084
1085 if x is not None:
1086 reveal_type(x) # N: Revealed type is "__main__.Foo"
1087 else:
1088 reveal_type(x) # N: Revealed type is "None"
1089
1090 if x is Foo.A:
1091 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
1092 else:
1093 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B] | Literal[__main__.Foo.C] | None"
1094 reveal_type(x) # N: Revealed type is "__main__.Foo | None"
1095 [builtins fixtures/enum.pyi]
1096
1097 [case testEnumReachabilityWithMultipleEnums]
1098 # flags: --warn-unreachable
1099 from enum import Enum
1100 from typing import Literal, Union
1101
1102 class Foo(Enum):
1103 A = 1
1104 B = 2
1105 class Bar(Enum):
1106 A = 1
1107 B = 2
1108
1109 x1: Union[Foo, Bar]
1110 if x1 is Foo.A:
1111 reveal_type(x1) # N: Revealed type is "Literal[__main__.Foo.A]"
1112 else:
1113 reveal_type(x1) # N: Revealed type is "Literal[__main__.Foo.B] | __main__.Bar"
1114 reveal_type(x1) # N: Revealed type is "__main__.Foo | __main__.Bar"
1115
1116 x2: Union[Foo, Bar]
1117 if x2 is Bar.A:
1118 reveal_type(x2) # N: Revealed type is "Literal[__main__.Bar.A]"
1119 else:
1120 reveal_type(x2) # N: Revealed type is "__main__.Foo | Literal[__main__.Bar.B]"
1121 reveal_type(x2) # N: Revealed type is "__main__.Foo | __main__.Bar"
1122
1123 x3: Union[Foo, Bar]
1124 if x3 is Foo.A or x3 is Bar.A:
1125 reveal_type(x3) # N: Revealed type is "Literal[__main__.Foo.A] | Literal[__main__.Bar.A]"
1126 else:
1127 reveal_type(x3) # N: Revealed type is "Literal[__main__.Foo.B] | Literal[__main__.Bar.B]"
1128 reveal_type(x3) # N: Revealed type is "__main__.Foo | __main__.Bar"
1129
1130 [builtins fixtures/bool.pyi]
1131
1132 [case testEnumReachabilityPEP484ExampleWithFinal]
1133 # flags: --warn-unreachable
1134 from typing import Final, Union
1135 from enum import Enum
1136
1137 class Empty(Enum):
1138 token = 0
1139 _empty: Final = Empty.token
1140
1141 def func(x: Union[int, None, Empty] = _empty) -> int:
1142 boom = x + 42 # E: Unsupported left operand type for + ("None") \
1143 # E: Unsupported left operand type for + ("Empty") \
1144 # N: Left operand is of type "int | Empty | None"
1145 if x is _empty:
1146 reveal_type(x) # N: Revealed type is "Literal[__main__.Empty.token]"
1147 return 0
1148 elif x is None:
1149 reveal_type(x) # N: Revealed type is "None"
1150 return 1
1151 else: # At this point typechecker knows that x can only have type int
1152 reveal_type(x) # N: Revealed type is "builtins.int"
1153 return x + 2
1154 [builtins fixtures/primitives.pyi]
1155
1156 [case testEnumReachabilityPEP484ExampleWithMultipleValues]
1157 # flags: --warn-unreachable
1158 from typing import Union
1159 from enum import Enum
1160
1161 class Reason(Enum):
1162 timeout = 1
1163 error = 2
1164
1165 def process(response: Union[str, Reason] = '') -> str:
1166 if response is Reason.timeout:
1167 reveal_type(response) # N: Revealed type is "Literal[__main__.Reason.timeout]"
1168 return 'TIMEOUT'
1169 elif response is Reason.error:
1170 reveal_type(response) # N: Revealed type is "Literal[__main__.Reason.error]"
1171 return 'ERROR'
1172 else:
1173 # response can be only str, all other possible values exhausted
1174 reveal_type(response) # N: Revealed type is "builtins.str"
1175 return 'PROCESSED: ' + response
1176 [builtins fixtures/primitives.pyi]
1177
1178
1179 [case testEnumReachabilityPEP484ExampleSingleton]
1180 # flags: --warn-unreachable
1181 from typing import Final, Union
1182 from enum import Enum
1183
1184 class Empty(Enum):
1185 token = 0
1186 _empty = Empty.token
1187
1188 def func(x: Union[int, None, Empty] = _empty) -> int:
1189 boom = x + 42 # E: Unsupported left operand type for + ("None") \
1190 # E: Unsupported left operand type for + ("Empty") \
1191 # N: Left operand is of type "int | Empty | None"
1192 if x is _empty:
1193 reveal_type(x) # N: Revealed type is "Literal[__main__.Empty.token]"
1194 return 0
1195 elif x is None:
1196 reveal_type(x) # N: Revealed type is "None"
1197 return 1
1198 else: # At this point typechecker knows that x can only have type int
1199 reveal_type(x) # N: Revealed type is "builtins.int"
1200 return x + 2
1201 [builtins fixtures/primitives.pyi]
1202
1203 [case testEnumReachabilityPEP484ExampleSingletonWithMethod]
1204 # flags: --python-version 3.11 --warn-unreachable
1205 from typing import Final, Union
1206 from enum import Enum, member
1207
1208 class Empty(Enum):
1209 # note, that without `member` we cannot tell that `token` is a member:
1210 token = member(lambda x: x)
1211
1212 def f(self) -> int:
1213 return 1
1214
1215 _empty = Empty.token
1216 reveal_type(_empty) # N: Revealed type is "__main__.Empty"
1217 reveal_type(Empty.f) # N: Revealed type is "def (self: __main__.Empty) -> builtins.int"
1218
1219 def func(x: Union[int, None, Empty] = _empty) -> int:
1220 boom = x + 42 # E: Unsupported left operand type for + ("None") \
1221 # E: Unsupported left operand type for + ("Empty") \
1222 # N: Left operand is of type "int | Empty | None"
1223 if x is _empty:
1224 reveal_type(x) # N: Revealed type is "Literal[__main__.Empty.token]"
1225 return 0
1226 elif x is None:
1227 reveal_type(x) # N: Revealed type is "None"
1228 return 1
1229 else: # At this point typechecker knows that x can only have type int
1230 reveal_type(x) # N: Revealed type is "builtins.int"
1231 return x + 2
1232 [builtins fixtures/primitives.pyi]
1233
1234 [case testAssignEnumAsAttribute]
1235 from enum import Enum
1236
1237 class A:
1238 def __init__(self) -> None:
1239 self.b = Enum("b", [("foo", "bar")]) # E: Enum type as attribute is not supported
1240
1241 reveal_type(A().b) # N: Revealed type is "Any"
1242 [builtins fixtures/enum.pyi]
1243
1244 [case testEnumReachabilityWithChaining]
1245 # flags: --warn-unreachable
1246 from enum import Enum
1247
1248 class Foo(Enum):
1249 A = 1
1250 B = 2
1251
1252 x: Foo
1253 y: Foo
1254
1255 # We can't narrow anything in the else cases -- what if
1256 # x is Foo.A and y is Foo.B or vice versa, for example?
1257 if x is y is Foo.A:
1258 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
1259 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
1260 elif x is y is Foo.B:
1261 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
1262 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
1263 else:
1264 reveal_type(x) # N: Revealed type is "__main__.Foo"
1265 reveal_type(y) # N: Revealed type is "__main__.Foo"
1266 reveal_type(x) # N: Revealed type is "__main__.Foo"
1267 reveal_type(y) # N: Revealed type is "__main__.Foo"
1268
1269 if x is Foo.A is y:
1270 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
1271 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
1272 elif x is Foo.B is y:
1273 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
1274 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
1275 else:
1276 reveal_type(x) # N: Revealed type is "__main__.Foo"
1277 reveal_type(y) # N: Revealed type is "__main__.Foo"
1278 reveal_type(x) # N: Revealed type is "__main__.Foo"
1279 reveal_type(y) # N: Revealed type is "__main__.Foo"
1280
1281 if Foo.A is x is y:
1282 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
1283 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
1284 elif Foo.B is x is y:
1285 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
1286 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
1287 else:
1288 reveal_type(x) # N: Revealed type is "__main__.Foo"
1289 reveal_type(y) # N: Revealed type is "__main__.Foo"
1290 reveal_type(x) # N: Revealed type is "__main__.Foo"
1291 reveal_type(y) # N: Revealed type is "__main__.Foo"
1292
1293 [builtins fixtures/primitives.pyi]
1294
1295 [case testEnumReachabilityWithChainingDisjoint]
1296 # flags: --warn-unreachable
1297 from enum import Enum
1298
1299 class Foo(Enum):
1300 A = 1
1301 B = 2
1302
1303 # Used to divide up a chained comparison into multiple identity groups
1304 def __lt__(self, other: object) -> bool: return True
1305
1306 x: Foo
1307 y: Foo
1308
1309 # No conflict
1310 if x is Foo.A < y is Foo.B:
1311 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
1312 reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
1313 else:
1314 # Note: we can't narrow in this case. What if both x and y
1315 # are Foo.A, for example?
1316 reveal_type(x) # N: Revealed type is "__main__.Foo"
1317 reveal_type(y) # N: Revealed type is "__main__.Foo"
1318 reveal_type(x) # N: Revealed type is "__main__.Foo"
1319 reveal_type(y) # N: Revealed type is "__main__.Foo"
1320
1321 # The standard output when we end up inferring two disjoint facts about the same expr
1322 if x is Foo.A and x is Foo.B:
1323 reveal_type(x) # E: Statement is unreachable
1324 else:
1325 reveal_type(x) # N: Revealed type is "__main__.Foo"
1326 reveal_type(x) # N: Revealed type is "__main__.Foo"
1327
1328 # ..and we get the same result if we have two disjoint groups within the same comp expr
1329 if x is Foo.A < x is Foo.B:
1330 reveal_type(x) # E: Statement is unreachable
1331 else:
1332 reveal_type(x) # N: Revealed type is "__main__.Foo"
1333 reveal_type(x) # N: Revealed type is "__main__.Foo"
1334 [builtins fixtures/primitives.pyi]
1335
1336 [case testEnumReachabilityWithChainingDirectConflict]
1337 # flags: --warn-unreachable
1338 from enum import Enum
1339 from typing import Final, Literal
1340
1341 class Foo(Enum):
1342 A = 1
1343 B = 2
1344 C = 3
1345
1346 x: Foo
1347 if x is Foo.A is Foo.B:
1348 reveal_type(x) # E: Statement is unreachable
1349 else:
1350 reveal_type(x) # N: Revealed type is "__main__.Foo"
1351 reveal_type(x) # N: Revealed type is "__main__.Foo"
1352
1353 literal_a: Literal[Foo.A]
1354 literal_b: Literal[Foo.B]
1355 if x is literal_a is literal_b:
1356 reveal_type(x) # E: Statement is unreachable
1357 else:
1358 reveal_type(x) # N: Revealed type is "__main__.Foo"
1359 reveal_type(x) # N: Revealed type is "__main__.Foo"
1360
1361 final_a: Final = Foo.A
1362 final_b: Final = Foo.B
1363 if x is final_a is final_b:
1364 reveal_type(x) # E: Statement is unreachable
1365 else:
1366 reveal_type(x) # N: Revealed type is "__main__.Foo"
1367 reveal_type(x) # N: Revealed type is "__main__.Foo"
1368
1369 [builtins fixtures/primitives.pyi]
1370
1371 [case testEnumReachabilityWithChainingBigDisjoints]
1372 # flags: --warn-unreachable
1373 from enum import Enum
1374 from typing import Final, Literal
1375
1376 class Foo(Enum):
1377 A = 1
1378 B = 2
1379 C = 3
1380
1381 def __lt__(self, other: object) -> bool: return True
1382
1383 x0: Foo
1384 x1: Foo
1385 x2: Foo
1386 x3: Foo
1387 x4: Foo
1388 x5: Foo
1389
1390 if x0 is x1 is Foo.A is x2 < x3 is Foo.B is x4 is x5:
1391 reveal_type(x0) # N: Revealed type is "Literal[__main__.Foo.A]"
1392 reveal_type(x1) # N: Revealed type is "Literal[__main__.Foo.A]"
1393 reveal_type(x2) # N: Revealed type is "Literal[__main__.Foo.A]"
1394
1395 reveal_type(x3) # N: Revealed type is "Literal[__main__.Foo.B]"
1396 reveal_type(x4) # N: Revealed type is "Literal[__main__.Foo.B]"
1397 reveal_type(x5) # N: Revealed type is "Literal[__main__.Foo.B]"
1398 else:
1399 # We unfortunately can't narrow away anything. For example,
1400 # what if x0 == Foo.A and x1 == Foo.B or vice versa?
1401 reveal_type(x0) # N: Revealed type is "__main__.Foo"
1402 reveal_type(x1) # N: Revealed type is "__main__.Foo"
1403 reveal_type(x2) # N: Revealed type is "__main__.Foo"
1404
1405 reveal_type(x3) # N: Revealed type is "__main__.Foo"
1406 reveal_type(x4) # N: Revealed type is "__main__.Foo"
1407 reveal_type(x5) # N: Revealed type is "__main__.Foo"
1408 [builtins fixtures/primitives.pyi]
1409
1410 [case testPrivateAttributeNotAsEnumMembers]
1411 import enum
1412
1413 class Comparator(enum.Enum):
1414 LessThan = "<"
1415 LessThanOrEqualTo = "<="
1416 EqualTo = "=="
1417 NotEqualTo = "!="
1418 GreaterThanOrEqualTo = ">="
1419 GreaterThan = ">"
1420
1421 __foo__ = {
1422 LessThan: 1,
1423 LessThanOrEqualTo: 2,
1424 EqualTo: 3,
1425 NotEqualTo: 4,
1426 GreaterThanOrEqualTo: 5,
1427 GreaterThan: 6,
1428 }
1429
1430 def foo(self) -> int:
1431 return Comparator.__foo__[self.value]
1432
1433 reveal_type(Comparator.__foo__) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
1434 [builtins fixtures/dict.pyi]
1435
1436 [case testEnumClassAttributeUnannotated]
1437 import enum
1438 from typing import ClassVar, Literal
1439
1440 class MyEnum(enum.Enum):
1441 foo: ClassVar[str]
1442 bar: str
1443
1444 VALUE_A = 1
1445 VALUE_B = 2
1446
1447 reveal_type(MyEnum.foo) # N: Revealed type is "builtins.str"
1448 reveal_type(MyEnum.bar) # N: Revealed type is "builtins.str"
1449 x: Literal[MyEnum.foo] # E: Parameter 1 of Literal[...] is invalid
1450 y: Literal[MyEnum.bar] # E: Parameter 1 of Literal[...] is invalid
1451 [builtins fixtures/enum.pyi]
1452
1453 [case testEnumAttributesInheritedFromMixin]
1454 from enum import Enum
1455 from typing import TYPE_CHECKING, ClassVar, Final, Literal
1456
1457 class A:
1458 var1 = 1
1459 var2: ClassVar[str]
1460 var3: Final[int] = 3
1461 var4: str
1462
1463 class E(A, Enum):
1464 mem = 1
1465
1466 reveal_type(E.var1) # N: Revealed type is "builtins.int"
1467 reveal_type(E.var2) # N: Revealed type is "builtins.str"
1468 reveal_type(E.var3) # N: Revealed type is "builtins.int"
1469 reveal_type(E.var4) # N: Revealed type is "builtins.str"
1470 reveal_type(E.mem) # N: Revealed type is "Literal[__main__.E.mem]?"
1471
1472 E.var1.value # E: "int" has no attribute "value"
1473 E.var2.name # E: "str" has no attribute "name"
1474 E.mem.name
1475
1476 x1: Literal[E.var1] # E: Parameter 1 of Literal[...] is invalid
1477 x2: Literal[E.var2] # E: Parameter 1 of Literal[...] is invalid
1478 x3: Literal[E.var3] # E: Parameter 1 of Literal[...] is invalid
1479 x4: Literal[E.var4] # E: Parameter 1 of Literal[...] is invalid
1480 m: Literal[E.mem]
1481 [builtins fixtures/enum.pyi]
1482
1483 [case testEnumWithInstanceAttributes]
1484 from enum import Enum
1485 class Foo(Enum):
1486 def __init__(self, value: int) -> None:
1487 self.foo = "bar"
1488 A = 1
1489 B = 2
1490
1491 a = Foo.A
1492 reveal_type(a.value) # N: Revealed type is "Literal[1]? | Literal[2]?"
1493 reveal_type(a._value_) # N: Revealed type is "Literal[1]? | Literal[2]?"
1494 [builtins fixtures/enum.pyi]
1495
1496 [case testNewSetsUnexpectedValueType]
1497 from enum import Enum
1498
1499 class bytes:
1500 def __new__(cls): pass
1501
1502 class Foo(bytes, Enum):
1503 def __new__(cls, value: int) -> 'Foo':
1504 obj = bytes.__new__(cls)
1505 obj._value_ = "Number %d" % value
1506 return obj
1507 A = 1
1508 B = 2
1509
1510 a = Foo.A
1511 reveal_type(a.value) # N: Revealed type is "Any"
1512 reveal_type(a._value_) # N: Revealed type is "Any"
1513 [builtins fixtures/tuple.pyi]
1514 [typing fixtures/typing-medium.pyi]
1515
1516 [case testValueTypeWithNewInParentClass]
1517 from enum import Enum
1518
1519 class bytes:
1520 def __new__(cls): pass
1521
1522 class Foo(bytes, Enum):
1523 def __new__(cls, value: int) -> 'Foo':
1524 obj = bytes.__new__(cls)
1525 obj._value_ = "Number %d" % value
1526 return obj
1527
1528 class Bar(Foo):
1529 A = 1
1530 B = 2
1531
1532 a = Bar.A
1533 reveal_type(a.value) # N: Revealed type is "Any"
1534 reveal_type(a._value_) # N: Revealed type is "Any"
1535 [builtins fixtures/primitives.pyi]
1536 [typing fixtures/typing-medium.pyi]
1537
1538 [case testValueTypeWithUserDataType]
1539 from enum import Enum
1540 from typing import Any
1541
1542 class Data:
1543 def __new__(cls, value: Any) -> Data: pass
1544
1545 class DataEnum(Data, Enum):
1546 A = Data(1)
1547
1548 reveal_type(DataEnum.A) # N: Revealed type is "Literal[__main__.DataEnum.A]?"
1549 reveal_type(DataEnum.A.value) # N: Revealed type is "__main__.Data"
1550 reveal_type(DataEnum.A._value_) # N: Revealed type is "__main__.Data"
1551 [builtins fixtures/tuple.pyi]
1552
1553 [case testEnumNarrowedToTwoLiterals]
1554 # Regression test: two literals of an enum would be joined
1555 # as the full type, regardless of the amount of elements
1556 # the enum contains.
1557 from enum import Enum
1558 from typing import Literal, Union
1559
1560 class Foo(Enum):
1561 A = 1
1562 B = 2
1563 C = 3
1564
1565 def f(x: Foo):
1566 if x is Foo.A:
1567 return x
1568 if x is Foo.B:
1569 pass
1570 reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B] | Literal[__main__.Foo.C]"
1571
1572 [builtins fixtures/bool.pyi]
1573
1574 [case testEnumTypeCompatibleWithLiteralUnion]
1575 from enum import Enum
1576 from typing import Literal
1577
1578 class E(Enum):
1579 A = 1
1580 B = 2
1581 C = 3
1582
1583 e: E
1584 a: Literal[E.A, E.B, E.C] = e
1585 b: Literal[E.A, E.B] = e # E: Incompatible types in assignment (expression has type "E", variable has type "Literal[E.A, E.B]")
1586 c: Literal[E.A, E.C] = e # E: Incompatible types in assignment (expression has type "E", variable has type "Literal[E.A, E.C]")
1587 b = a # E: Incompatible types in assignment (expression has type "Literal[E.A, E.B, E.C]", variable has type "Literal[E.A, E.B]")
1588 [builtins fixtures/bool.pyi]
1589
1590 [case testIntEnumWithNewTypeValue]
1591 from typing import NewType
1592 from enum import IntEnum
1593
1594 N = NewType("N", int)
1595
1596 class E(IntEnum):
1597 A = N(0)
1598
1599 reveal_type(E.A.value) # N: Revealed type is "__main__.N"
1600 [builtins fixtures/enum.pyi]
1601
1602
1603 [case testEnumFinalValues]
1604 from enum import Enum
1605 class Medal(Enum):
1606 gold = 1
1607 silver = 2
1608
1609 # Another value:
1610 Medal.gold = 0 # E: Cannot assign to final attribute "gold"
1611 # Same value:
1612 Medal.silver = 2 # E: Cannot assign to final attribute "silver"
1613 [builtins fixtures/enum.pyi]
1614
1615
1616 [case testEnumFinalValuesCannotRedefineValueProp]
1617 from enum import Enum
1618 class Types(Enum):
1619 key = 0
1620 value = 1
1621 [builtins fixtures/enum.pyi]
1622
1623
1624 [case testEnumReusedKeys]
1625 # https://github.com/python/mypy/issues/11248
1626 from enum import Enum
1627 class Correct(Enum):
1628 x = 'y'
1629 y = 'x'
1630 class Correct2(Enum):
1631 x = 'y'
1632 __z = 'y'
1633 __z = 'x'
1634 class Foo(Enum):
1635 A = 1
1636 A = 'a' # E: Attempted to reuse member name "A" in Enum definition "Foo" \
1637 # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1638 reveal_type(Foo.A.value) # N: Revealed type is "Literal[1]?"
1639
1640 class Bar(Enum):
1641 A = 1
1642 B = A = 2 # E: Attempted to reuse member name "A" in Enum definition "Bar"
1643 class Baz(Enum):
1644 A = 1
1645 B, A = (1, 2) # E: Attempted to reuse member name "A" in Enum definition "Baz"
1646 [builtins fixtures/tuple.pyi]
1647
1648 [case testEnumReusedKeysOverlapWithLocalVar]
1649 from enum import Enum
1650 x = 1
1651 class Foo(Enum):
1652 x = 2
1653 def method(self) -> None:
1654 x = 3
1655 x = 4
1656 [builtins fixtures/bool.pyi]
1657
1658 [case testEnumImplicitlyFinalForSubclassing]
1659 from enum import Enum, IntEnum, Flag, IntFlag
1660
1661 class NonEmptyEnum(Enum):
1662 x = 1
1663 class NonEmptyIntEnum(IntEnum):
1664 x = 1
1665 class NonEmptyFlag(Flag):
1666 x = 1
1667 class NonEmptyIntFlag(IntFlag):
1668 x = 1
1669
1670 class ErrorEnumWithValue(NonEmptyEnum): # E: Cannot extend enum with existing members: "NonEmptyEnum"
1671 x = 1 # E: Cannot override final attribute "x" (previously declared in base class "NonEmptyEnum")
1672 class ErrorIntEnumWithValue(NonEmptyIntEnum): # E: Cannot extend enum with existing members: "NonEmptyIntEnum"
1673 x = 1 # E: Cannot override final attribute "x" (previously declared in base class "NonEmptyIntEnum")
1674 class ErrorFlagWithValue(NonEmptyFlag): # E: Cannot extend enum with existing members: "NonEmptyFlag"
1675 x = 1 # E: Cannot override final attribute "x" (previously declared in base class "NonEmptyFlag")
1676 class ErrorIntFlagWithValue(NonEmptyIntFlag): # E: Cannot extend enum with existing members: "NonEmptyIntFlag"
1677 x = 1 # E: Cannot override final attribute "x" (previously declared in base class "NonEmptyIntFlag")
1678
1679 class ErrorEnumWithoutValue(NonEmptyEnum): # E: Cannot extend enum with existing members: "NonEmptyEnum"
1680 pass
1681 class ErrorIntEnumWithoutValue(NonEmptyIntEnum): # E: Cannot extend enum with existing members: "NonEmptyIntEnum"
1682 pass
1683 class ErrorFlagWithoutValue(NonEmptyFlag): # E: Cannot extend enum with existing members: "NonEmptyFlag"
1684 pass
1685 class ErrorIntFlagWithoutValue(NonEmptyIntFlag): # E: Cannot extend enum with existing members: "NonEmptyIntFlag"
1686 pass
1687 [builtins fixtures/bool.pyi]
1688
1689 [case testEnumImplicitlyFinalForSubclassingWithCallableMember]
1690 # flags: --python-version 3.11
1691 from enum import Enum, IntEnum, Flag, IntFlag, member
1692
1693 class NonEmptyEnum(Enum):
1694 @member
1695 def call(self) -> None: ...
1696 class NonEmptyIntEnum(IntEnum):
1697 @member
1698 def call(self) -> None: ...
1699 class NonEmptyFlag(Flag):
1700 @member
1701 def call(self) -> None: ...
1702 class NonEmptyIntFlag(IntFlag):
1703 @member
1704 def call(self) -> None: ...
1705
1706 class ErrorEnumWithoutValue(NonEmptyEnum): # E: Cannot extend enum with existing members: "NonEmptyEnum"
1707 pass
1708 class ErrorIntEnumWithoutValue(NonEmptyIntEnum): # E: Cannot extend enum with existing members: "NonEmptyIntEnum"
1709 pass
1710 class ErrorFlagWithoutValue(NonEmptyFlag): # E: Cannot extend enum with existing members: "NonEmptyFlag"
1711 pass
1712 class ErrorIntFlagWithoutValue(NonEmptyIntFlag): # E: Cannot extend enum with existing members: "NonEmptyIntFlag"
1713 pass
1714 [builtins fixtures/bool.pyi]
1715
1716 [case testEnumCanExtendEnumsWithNonMembers]
1717 # flags: --python-version 3.11
1718 from enum import Enum, IntEnum, Flag, IntFlag, nonmember
1719
1720 class NonEmptyEnum(Enum):
1721 x = nonmember(1)
1722 class NonEmptyIntEnum(IntEnum):
1723 x = nonmember(1)
1724 class NonEmptyFlag(Flag):
1725 x = nonmember(1)
1726 class NonEmptyIntFlag(IntFlag):
1727 x = nonmember(1)
1728
1729 class ErrorEnumWithoutValue(NonEmptyEnum):
1730 pass
1731 class ErrorIntEnumWithoutValue(NonEmptyIntEnum):
1732 pass
1733 class ErrorFlagWithoutValue(NonEmptyFlag):
1734 pass
1735 class ErrorIntFlagWithoutValue(NonEmptyIntFlag):
1736 pass
1737 [builtins fixtures/bool.pyi]
1738
1739 [case testLambdaIsNotEnumMember]
1740 from enum import Enum
1741
1742 class My(Enum):
1743 x = lambda a: a
1744
1745 class Other(My): ...
1746 [builtins fixtures/bool.pyi]
1747
1748 [case testSubclassingNonFinalEnums]
1749 from enum import Enum, IntEnum, Flag, IntFlag, EnumMeta
1750
1751 def decorator(func):
1752 return func
1753
1754 class EmptyEnum(Enum):
1755 pass
1756 class EmptyIntEnum(IntEnum):
1757 pass
1758 class EmptyFlag(Flag):
1759 pass
1760 class EmptyIntFlag(IntFlag):
1761 pass
1762 class EmptyEnumMeta(EnumMeta):
1763 pass
1764
1765 class NonEmptyEnumSub(EmptyEnum):
1766 x = 1
1767 class NonEmptyIntEnumSub(EmptyIntEnum):
1768 x = 1
1769 class NonEmptyFlagSub(EmptyFlag):
1770 x = 1
1771 class NonEmptyIntFlagSub(EmptyIntFlag):
1772 x = 1
1773 class NonEmptyEnumMetaSub(EmptyEnumMeta):
1774 x = 1
1775
1776 class EmptyEnumSub(EmptyEnum):
1777 def method(self) -> None: pass
1778 @decorator
1779 def other(self) -> None: pass
1780 class EmptyIntEnumSub(EmptyIntEnum):
1781 def method(self) -> None: pass
1782 class EmptyFlagSub(EmptyFlag):
1783 def method(self) -> None: pass
1784 class EmptyIntFlagSub(EmptyIntFlag):
1785 def method(self) -> None: pass
1786 class EmptyEnumMetaSub(EmptyEnumMeta):
1787 def method(self) -> None: pass
1788
1789 class NestedEmptyEnumSub(EmptyEnumSub):
1790 x = 1
1791 class NestedEmptyIntEnumSub(EmptyIntEnumSub):
1792 x = 1
1793 class NestedEmptyFlagSub(EmptyFlagSub):
1794 x = 1
1795 class NestedEmptyIntFlagSub(EmptyIntFlagSub):
1796 x = 1
1797 class NestedEmptyEnumMetaSub(EmptyEnumMetaSub):
1798 x = 1
1799 [builtins fixtures/bool.pyi]
1800
1801 [case testEnumExplicitlyAndImplicitlyFinal]
1802 from typing import final
1803 from enum import Enum, IntEnum, Flag, IntFlag, EnumMeta
1804
1805 @final
1806 class EmptyEnum(Enum):
1807 pass
1808 @final
1809 class EmptyIntEnum(IntEnum):
1810 pass
1811 @final
1812 class EmptyFlag(Flag):
1813 pass
1814 @final
1815 class EmptyIntFlag(IntFlag):
1816 pass
1817 @final
1818 class EmptyEnumMeta(EnumMeta):
1819 pass
1820
1821 class EmptyEnumSub(EmptyEnum): # E: Cannot inherit from final class "EmptyEnum"
1822 pass
1823 class EmptyIntEnumSub(EmptyIntEnum): # E: Cannot inherit from final class "EmptyIntEnum"
1824 pass
1825 class EmptyFlagSub(EmptyFlag): # E: Cannot inherit from final class "EmptyFlag"
1826 pass
1827 class EmptyIntFlagSub(EmptyIntFlag): # E: Cannot inherit from final class "EmptyIntFlag"
1828 pass
1829 class EmptyEnumMetaSub(EmptyEnumMeta): # E: Cannot inherit from final class "EmptyEnumMeta"
1830 pass
1831
1832 @final
1833 class NonEmptyEnum(Enum):
1834 x = 1
1835 @final
1836 class NonEmptyIntEnum(IntEnum):
1837 x = 1
1838 @final
1839 class NonEmptyFlag(Flag):
1840 x = 1
1841 @final
1842 class NonEmptyIntFlag(IntFlag):
1843 x = 1
1844 @final
1845 class NonEmptyEnumMeta(EnumMeta):
1846 x = 1
1847
1848 class ErrorEnumWithoutValue(NonEmptyEnum): # E: Cannot inherit from final class "NonEmptyEnum" \
1849 # E: Cannot extend enum with existing members: "NonEmptyEnum"
1850 pass
1851 class ErrorIntEnumWithoutValue(NonEmptyIntEnum): # E: Cannot inherit from final class "NonEmptyIntEnum" \
1852 # E: Cannot extend enum with existing members: "NonEmptyIntEnum"
1853 pass
1854 class ErrorFlagWithoutValue(NonEmptyFlag): # E: Cannot inherit from final class "NonEmptyFlag" \
1855 # E: Cannot extend enum with existing members: "NonEmptyFlag"
1856 pass
1857 class ErrorIntFlagWithoutValue(NonEmptyIntFlag): # E: Cannot inherit from final class "NonEmptyIntFlag" \
1858 # E: Cannot extend enum with existing members: "NonEmptyIntFlag"
1859 pass
1860 class ErrorEnumMetaWithoutValue(NonEmptyEnumMeta): # E: Cannot inherit from final class "NonEmptyEnumMeta"
1861 pass
1862 [builtins fixtures/bool.pyi]
1863
1864 [case testEnumFinalSubtypingEnumMetaSpecialCase]
1865 from enum import EnumMeta
1866 # `EnumMeta` types are not `Enum`s
1867 class SubMeta(EnumMeta):
1868 x = 1
1869 class SubSubMeta(SubMeta):
1870 x = 2
1871 [builtins fixtures/bool.pyi]
1872
1873 [case testEnumFinalSubtypingOverloadedSpecialCase]
1874 from typing import overload
1875 from enum import Enum, IntEnum, Flag, IntFlag, EnumMeta
1876
1877 class EmptyEnum(Enum):
1878 @overload
1879 def method(self, arg: int) -> int:
1880 pass
1881 @overload
1882 def method(self, arg: str) -> str:
1883 pass
1884 def method(self, arg):
1885 pass
1886 class EmptyIntEnum(IntEnum):
1887 @overload
1888 def method(self, arg: int) -> int:
1889 pass
1890 @overload
1891 def method(self, arg: str) -> str:
1892 pass
1893 def method(self, arg):
1894 pass
1895 class EmptyFlag(Flag):
1896 @overload
1897 def method(self, arg: int) -> int:
1898 pass
1899 @overload
1900 def method(self, arg: str) -> str:
1901 pass
1902 def method(self, arg):
1903 pass
1904 class EmptyIntFlag(IntFlag):
1905 @overload
1906 def method(self, arg: int) -> int:
1907 pass
1908 @overload
1909 def method(self, arg: str) -> str:
1910 pass
1911 def method(self, arg):
1912 pass
1913 class EmptyEnumMeta(EnumMeta):
1914 @overload
1915 def method(self, arg: int) -> int:
1916 pass
1917 @overload
1918 def method(self, arg: str) -> str:
1919 pass
1920 def method(self, arg):
1921 pass
1922
1923 class NonEmptyEnumSub(EmptyEnum):
1924 x = 1
1925 class NonEmptyIntEnumSub(EmptyIntEnum):
1926 x = 1
1927 class NonEmptyFlagSub(EmptyFlag):
1928 x = 1
1929 class NonEmptyIntFlagSub(EmptyIntFlag):
1930 x = 1
1931 class NonEmptyEnumMetaSub(EmptyEnumMeta):
1932 x = 1
1933 [builtins fixtures/bool.pyi]
1934
1935 [case testEnumFinalSubtypingMethodAndValueSpecialCase]
1936 from enum import Enum, IntEnum, Flag, IntFlag, EnumMeta
1937
1938 def decorator(func):
1939 return func
1940
1941 class NonEmptyEnum(Enum):
1942 x = 1
1943 def method(self) -> None: pass
1944 @decorator
1945 def other(self) -> None: pass
1946 class NonEmptyIntEnum(IntEnum):
1947 x = 1
1948 def method(self) -> None: pass
1949 class NonEmptyFlag(Flag):
1950 x = 1
1951 def method(self) -> None: pass
1952 class NonEmptyIntFlag(IntFlag):
1953 x = 1
1954 def method(self) -> None: pass
1955
1956 class ErrorEnumWithoutValue(NonEmptyEnum): # E: Cannot extend enum with existing members: "NonEmptyEnum"
1957 pass
1958 class ErrorIntEnumWithoutValue(NonEmptyIntEnum): # E: Cannot extend enum with existing members: "NonEmptyIntEnum"
1959 pass
1960 class ErrorFlagWithoutValue(NonEmptyFlag): # E: Cannot extend enum with existing members: "NonEmptyFlag"
1961 pass
1962 class ErrorIntFlagWithoutValue(NonEmptyIntFlag): # E: Cannot extend enum with existing members: "NonEmptyIntFlag"
1963 pass
1964 [builtins fixtures/bool.pyi]
1965
1966 [case testFinalEnumWithClassDef]
1967 from enum import Enum
1968
1969 class A(Enum):
1970 class Inner: pass
1971 class B(A): pass # E: Cannot extend enum with existing members: "A"
1972
1973 class A1(Enum):
1974 class __Inner: pass
1975 class B1(A1): pass
1976 [builtins fixtures/bool.pyi]
1977
1978 [case testEnumFinalSpecialProps]
1979 # https://github.com/python/mypy/issues/11699
1980 # https://github.com/python/mypy/issues/11820
1981 from enum import Enum, IntEnum
1982
1983 class BaseWithSpecials:
1984 __slots__ = ()
1985 __doc__ = 'doc'
1986 __module__ = 'module'
1987 __annotations__ = {'a': int}
1988 __dict__ = {'a': 1}
1989
1990 class E(BaseWithSpecials, Enum):
1991 name = 'a'
1992 value = 'b'
1993 _name_ = 'a1'
1994 _value_ = 'b2'
1995 _order_ = 'X Y'
1996 __order__ = 'X Y'
1997 __slots__ = ()
1998 __doc__ = 'doc'
1999 __module__ = 'module'
2000 __annotations__ = {'a': int}
2001 __dict__ = {'a': 1}
2002
2003 class EI(IntEnum):
2004 name = 'a'
2005 value = 1
2006 _name_ = 'a1'
2007 _value_ = 2
2008 _order_ = 'X Y'
2009 __order__ = 'X Y'
2010 __slots__ = ()
2011 __doc__ = 'doc'
2012 __module__ = 'module'
2013 __annotations__ = {'a': int}
2014 __dict__ = {'a': 1}
2015
2016 E._order_ = 'a' # E: Cannot assign to final attribute "_order_"
2017 EI.value = 2 # E: Cannot assign to final attribute "value"
2018 [builtins fixtures/dict.pyi]
2019
2020 [case testEnumNotFinalWithMethodsAndUninitializedValues]
2021 # https://github.com/python/mypy/issues/11578
2022 from enum import Enum
2023 from typing import Final
2024
2025 class A(Enum):
2026 x: int
2027 def method(self) -> int: pass
2028 class B(A):
2029 x = 1 # E: Cannot override writable attribute "x" with a final one \
2030 # E: Incompatible types in assignment (expression has type "B", base class "A" defined the type as "int")
2031
2032 class A1(Enum):
2033 x: int = 1 # E: Enum members must be left unannotated \
2034 # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members
2035 class B1(A1): # E: Cannot extend enum with existing members: "A1"
2036 pass
2037
2038 class A2(Enum):
2039 x = 2
2040 class B2(A2): # E: Cannot extend enum with existing members: "A2"
2041 pass
2042
2043 # We leave this `Final` without a value,
2044 # because we need to test annotation only mode:
2045 class A3(Enum):
2046 x: Final[int] # type: ignore
2047 class B3(A3):
2048 x = 1 # E: Cannot override final attribute "x" (previously declared in base class "A3") \
2049 # E: Incompatible types in assignment (expression has type "B3", base class "A3" defined the type as "int")
2050 [builtins fixtures/bool.pyi]
2051
2052 [case testEnumNotFinalWithMethodsAndUninitializedValuesStub]
2053 import lib
2054
2055 [file lib.pyi]
2056 from enum import Enum
2057 class A(Enum): # E: Detected enum "lib.A" in a type stub with zero members. There is a chance this is due to a recent change in the semantics of enum membership. If so, use `member = value` to mark an enum member, instead of `member: type` \
2058 # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members
2059 x: int
2060 class B(A):
2061 x = 1 # E: Cannot override writable attribute "x" with a final one \
2062 # E: Incompatible types in assignment (expression has type "B", base class "A" defined the type as "int")
2063
2064 class C(Enum):
2065 x = 1
2066 class D(C): # E: Cannot extend enum with existing members: "C" \
2067 # E: Detected enum "lib.D" in a type stub with zero members. There is a chance this is due to a recent change in the semantics of enum membership. If so, use `member = value` to mark an enum member, instead of `member: type` \
2068 # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members
2069 x: int # E: Incompatible types in assignment (expression has type "int", base class "C" defined the type as "C") \
2070 # E: Cannot assign to final name "x"
2071 [builtins fixtures/bool.pyi]
2072
2073 [case testEnumNotFinalWithMethodsAndUninitializedValuesStubMember]
2074 # flags: --python-version 3.11
2075 # This was added in 3.11
2076 import lib
2077
2078 [file lib.pyi]
2079 from enum import Enum, member
2080 class A(Enum):
2081 @member
2082 def x(self) -> None: ...
2083 [builtins fixtures/bool.pyi]
2084
2085 [case testEnumLiteralValues]
2086 from enum import Enum
2087
2088 class A(Enum):
2089 str = "foo"
2090 int = 1
2091 bool = False
2092 tuple = (1,)
2093
2094 reveal_type(A.str.value) # N: Revealed type is "Literal['foo']?"
2095 reveal_type(A.int.value) # N: Revealed type is "Literal[1]?"
2096 reveal_type(A.bool.value) # N: Revealed type is "Literal[False]?"
2097 reveal_type(A.tuple.value) # N: Revealed type is "tuple[Literal[1]?]"
2098 [builtins fixtures/tuple.pyi]
2099
2100 [case testFinalWithPrivateAssignment]
2101 import enum
2102 class Some(enum.Enum):
2103 __priv = 1
2104
2105 class Other(Some): # Should pass
2106 pass
2107 [builtins fixtures/tuple.pyi]
2108
2109 [case testFinalWithDunderAssignment]
2110 import enum
2111 class Some(enum.Enum):
2112 __some__ = 1
2113
2114 class Other(Some): # Should pass
2115 pass
2116 [builtins fixtures/tuple.pyi]
2117
2118 [case testFinalWithSunderAssignment]
2119 import enum
2120 class Some(enum.Enum):
2121 _some_ = 1
2122
2123 class Other(Some): # Should pass
2124 pass
2125 [builtins fixtures/tuple.pyi]
2126
2127 [case testFinalWithMethodAssignment]
2128 import enum
2129 from typing import overload
2130 class Some(enum.Enum):
2131 def lor(self, other) -> bool:
2132 pass
2133
2134 ror = lor
2135
2136 class Other(Some): # Should pass
2137 pass
2138
2139
2140 class WithOverload(enum.IntEnum):
2141 @overload
2142 def meth(self, arg: int) -> int: pass
2143 @overload
2144 def meth(self, arg: str) -> str: pass
2145 def meth(self, arg): pass
2146
2147 alias = meth
2148
2149 class SubWithOverload(WithOverload): # Should pass
2150 pass
2151 [builtins fixtures/tuple.pyi]
2152
2153 [case testEnumBaseClassesOrder]
2154 import enum
2155
2156 # Base types:
2157
2158 class First:
2159 def __new__(cls, val):
2160 pass
2161
2162 class Second:
2163 def __new__(cls, val):
2164 pass
2165
2166 class Third:
2167 def __new__(cls, val):
2168 pass
2169
2170 class Mixin:
2171 pass
2172
2173 class EnumWithCustomNew(enum.Enum):
2174 def __new__(cls, val):
2175 pass
2176
2177 class SecondEnumWithCustomNew(enum.Enum):
2178 def __new__(cls, val):
2179 pass
2180
2181 # Correct Enums:
2182
2183 class Correct0(enum.Enum):
2184 pass
2185
2186 class Correct1(Mixin, First, enum.Enum):
2187 pass
2188
2189 class Correct2(First, enum.Enum):
2190 pass
2191
2192 class Correct3(Mixin, enum.Enum):
2193 pass
2194
2195 class RegularClass(Mixin, First, Second):
2196 pass
2197
2198 class Correct5(enum.Enum):
2199 pass
2200
2201 # Correct inheritance:
2202
2203 class _InheritingDataAndMixin(Correct1):
2204 pass
2205
2206 class _CorrectWithData(First, Correct0):
2207 pass
2208
2209 class _CorrectWithDataAndMixin(Mixin, First, Correct0):
2210 pass
2211
2212 class _CorrectWithMixin(Mixin, Correct2):
2213 pass
2214
2215 class _CorrectMultipleEnumBases(Correct0, Correct5):
2216 pass
2217
2218 class _MultipleEnumBasesAndMixin(int, Correct0, enum.Flag):
2219 pass
2220
2221 class _MultipleEnumBasesWithCustomNew(int, EnumWithCustomNew, SecondEnumWithCustomNew):
2222 pass
2223
2224 # Wrong Enums:
2225
2226 class TwoDataTypesViaInheritance(Second, Correct2): # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Correct2"
2227 pass
2228
2229 class TwoDataTypesViaInheritanceAndMixin(Second, Correct2, Mixin): # E: No non-enum mixin classes are allowed after "__main__.Correct2" \
2230 # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Correct2"
2231 pass
2232
2233 class MixinAfterEnum1(enum.Enum, Mixin): # E: No non-enum mixin classes are allowed after "enum.Enum"
2234 pass
2235
2236 class MixinAfterEnum2(First, enum.Enum, Mixin): # E: No non-enum mixin classes are allowed after "enum.Enum"
2237 pass
2238
2239 class TwoDataTypes(First, Second, enum.Enum): # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second"
2240 pass
2241
2242 class TwoDataTypesAndIntEnumMixin(First, Second, enum.IntEnum, Mixin): # E: No non-enum mixin classes are allowed after "enum.IntEnum" \
2243 # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second"
2244 pass
2245
2246 class ThreeDataTypes(First, Second, Third, enum.Enum): # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second" \
2247 # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Third"
2248 pass
2249
2250 class ThreeDataTypesAndMixin(First, Second, Third, enum.Enum, Mixin): # E: No non-enum mixin classes are allowed after "enum.Enum" \
2251 # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second" \
2252 # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Third"
2253 pass
2254
2255 class FromEnumAndOther1(Correct2, Second, enum.Enum): # E: No non-enum mixin classes are allowed after "__main__.Correct2" \
2256 # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second"
2257 pass
2258
2259 class FromEnumAndOther2(Correct2, Second): # E: No non-enum mixin classes are allowed after "__main__.Correct2" \
2260 # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second"
2261 pass
2262 [builtins fixtures/tuple.pyi]
2263
2264 [case testRegression12258]
2265 from enum import Enum
2266
2267 class MyEnum(Enum): ...
2268
2269 class BytesEnum(bytes, MyEnum): ... # Should be ok
2270 [builtins fixtures/tuple.pyi]
2271
2272 [case testEnumWithNewHierarchy]
2273 import enum
2274
2275 class A:
2276 def __new__(cls, val): ...
2277 class B(A):
2278 def __new__(cls, val): ...
2279 class C:
2280 def __new__(cls, val): ...
2281
2282 class E1(A, enum.Enum): ...
2283 class E2(B, enum.Enum): ...
2284
2285 # Errors:
2286
2287 class W1(C, E1): ... # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.E1"
2288 class W2(C, E2): ... # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.E2"
2289 [builtins fixtures/tuple.pyi]
2290
2291 [case testEnumValueUnionSimplification]
2292 from enum import IntEnum
2293 from typing import Any
2294
2295 class C(IntEnum):
2296 X = 0
2297 Y = 1
2298 Z = 2
2299
2300 def f1(c: C) -> None:
2301 x = {'x': c.value}
2302 reveal_type(x) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
2303
2304 def f2(c: C, a: Any) -> None:
2305 x = {'x': c.value, 'y': a}
2306 reveal_type(x) # N: Revealed type is "builtins.dict[builtins.str, Any]"
2307 y = {'y': a, 'x': c.value}
2308 reveal_type(y) # N: Revealed type is "builtins.dict[builtins.str, Any]"
2309 [builtins fixtures/dict.pyi]
2310
2311 [case testEnumIgnoreIsDeleted]
2312 from enum import Enum
2313
2314 class C(Enum):
2315 _ignore_ = 'X'
2316
2317 C._ignore_ # E: "type[C]" has no attribute "_ignore_"
2318 [builtins fixtures/enum.pyi]
2319
2320 [case testCanOverrideDunderAttributes]
2321 import typing
2322 from enum import Enum, Flag
2323
2324 class BaseEnum(Enum):
2325 __dunder__ = 1
2326 __labels__: typing.Dict[int, str]
2327
2328 class Override(BaseEnum):
2329 __dunder__ = 2
2330 __labels__ = {1: "1"}
2331
2332 Override.__dunder__ = 3
2333 BaseEnum.__dunder__ = 3
2334 Override.__labels__ = {2: "2"}
2335
2336 class FlagBase(Flag):
2337 __dunder__ = 1
2338 __labels__: typing.Dict[int, str]
2339
2340 class FlagOverride(FlagBase):
2341 __dunder__ = 2
2342 __labels = {1: "1"}
2343
2344 FlagOverride.__dunder__ = 3
2345 FlagBase.__dunder__ = 3
2346 FlagOverride.__labels__ = {2: "2"}
2347 [builtins fixtures/dict.pyi]
2348
2349 [case testCanNotInitialize__members__]
2350 import typing
2351 from enum import Enum
2352
2353 class WritingMembers(Enum):
2354 __members__: typing.Dict[Enum, Enum] = {} # E: Assigned "__members__" will be overridden by "Enum" internally
2355
2356 class OnlyAnnotatedMembers(Enum):
2357 __members__: typing.Dict[Enum, Enum]
2358 [builtins fixtures/dict.pyi]
2359
2360 [case testCanOverrideDunderOnNonFirstBaseEnum]
2361 import typing
2362 from enum import Enum
2363
2364 class Some:
2365 __labels__: typing.Dict[int, str]
2366
2367 class A(Some, Enum):
2368 __labels__ = {1: "1"}
2369 [builtins fixtures/dict.pyi]
2370
2371 [case testEnumWithPartialTypes]
2372 from enum import Enum
2373
2374 class Mixed(Enum):
2375 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
2376 b = None
2377
2378 def check(self) -> None:
2379 reveal_type(Mixed.a.value) # N: Revealed type is "builtins.list[Any]"
2380 reveal_type(Mixed.b.value) # N: Revealed type is "None"
2381
2382 # Inferring Any here instead of a union seems to be a deliberate
2383 # choice; see the testEnumValueInhomogeneous case above.
2384 reveal_type(self.value) # N: Revealed type is "Any"
2385
2386 for field in Mixed:
2387 reveal_type(field.value) # N: Revealed type is "Any"
2388 if field.value is None:
2389 pass
2390
2391 class AllPartialList(Enum):
2392 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
2393 b = [] # E: Need type annotation for "b" (hint: "b: list[<type>] = ...")
2394
2395 def check(self) -> None:
2396 reveal_type(self.value) # N: Revealed type is "builtins.list[Any]"
2397 [builtins fixtures/tuple.pyi]
2398
2399 [case testEnumPrivateAttributeNotMember]
2400 from enum import Enum
2401
2402 class MyEnum(Enum):
2403 A = 1
2404 B = 2
2405 __my_dict = {A: "ham", B: "spam"}
2406
2407 # TODO: change the next line to use MyEnum._MyEnum__my_dict when mypy implements name mangling
2408 x: MyEnum = MyEnum.__my_dict # E: Incompatible types in assignment (expression has type "dict[int, str]", variable has type "MyEnum")
2409 [builtins fixtures/enum.pyi]
2410
2411 [case testEnumWithPrivateAttributeReachability]
2412 # flags: --warn-unreachable
2413 from enum import Enum
2414
2415 class MyEnum(Enum):
2416 A = 1
2417 B = 2
2418 __my_dict = {A: "ham", B: "spam"}
2419
2420 e: MyEnum
2421 if e == MyEnum.A:
2422 reveal_type(e) # N: Revealed type is "Literal[__main__.MyEnum.A]"
2423 elif e == MyEnum.B:
2424 reveal_type(e) # N: Revealed type is "Literal[__main__.MyEnum.B]"
2425 else:
2426 reveal_type(e) # E: Statement is unreachable
2427 [builtins fixtures/dict.pyi]
2428
2429
2430 [case testEnumNonMemberSupport]
2431 # flags: --python-version 3.11
2432 # This was added in 3.11
2433 from enum import Enum, nonmember
2434
2435 class My(Enum):
2436 a = 1
2437 b = 2
2438 c = nonmember(3)
2439
2440 reveal_type(My.a) # N: Revealed type is "Literal[__main__.My.a]?"
2441 reveal_type(My.b) # N: Revealed type is "Literal[__main__.My.b]?"
2442 reveal_type(My.c) # N: Revealed type is "builtins.int"
2443
2444 def accepts_my(my: My):
2445 reveal_type(my.value) # N: Revealed type is "Literal[1]? | Literal[2]?"
2446
2447 class Other(Enum):
2448 a = 1
2449 @nonmember
2450 class Support:
2451 b = 2
2452
2453 reveal_type(Other.a) # N: Revealed type is "Literal[__main__.Other.a]?"
2454 reveal_type(Other.Support.b) # N: Revealed type is "builtins.int"
2455 [builtins fixtures/dict.pyi]
2456
2457
2458 [case testEnumMemberSupport]
2459 # flags: --python-version 3.11
2460 # This was added in 3.11
2461 from enum import Enum, member
2462
2463 class A(Enum):
2464 x = member(1)
2465 y = 2
2466
2467 reveal_type(A.x) # N: Revealed type is "Literal[__main__.A.x]?"
2468 reveal_type(A.x.value) # N: Revealed type is "Literal[1]?"
2469 reveal_type(A.y) # N: Revealed type is "Literal[__main__.A.y]?"
2470 reveal_type(A.y.value) # N: Revealed type is "Literal[2]?"
2471
2472 def some_a(a: A):
2473 reveal_type(a.value) # N: Revealed type is "Literal[1]? | Literal[2]?"
2474 [builtins fixtures/dict.pyi]
2475
2476
2477 [case testEnumMemberAndNonMemberSupport]
2478 # flags: --python-version 3.11 --warn-unreachable
2479 # This was added in 3.11
2480 from enum import Enum, member, nonmember
2481
2482 class A(Enum):
2483 x = 1
2484 y = member(2)
2485 z = nonmember(3)
2486
2487 def some_a(a: A):
2488 if a is not A.x and a is not A.z:
2489 reveal_type(a) # N: Revealed type is "Literal[__main__.A.y]"
2490 if a is not A.y and a is not A.z:
2491 reveal_type(a) # N: Revealed type is "Literal[__main__.A.x]"
2492 if a is not A.x:
2493 reveal_type(a) # N: Revealed type is "Literal[__main__.A.y]"
2494 if a is not A.y:
2495 reveal_type(a) # N: Revealed type is "Literal[__main__.A.x]"
2496 [builtins fixtures/dict.pyi]
2497
2498 [case testEnumAccessFromInstance]
2499 # flags: --python-version 3.11 --warn-unreachable
2500 # This was added in 3.11
2501 from enum import Enum, member, nonmember
2502
2503 class A(Enum):
2504 x = 1
2505 y = member(2)
2506 z = nonmember(3)
2507
2508 reveal_type(A.x) # N: Revealed type is "Literal[__main__.A.x]?"
2509 reveal_type(A.y) # N: Revealed type is "Literal[__main__.A.y]?"
2510 reveal_type(A.z) # N: Revealed type is "builtins.int"
2511
2512 reveal_type(A.x.x) # N: Revealed type is "Literal[__main__.A.x]?"
2513 reveal_type(A.x.x.x) # N: Revealed type is "Literal[__main__.A.x]?"
2514 reveal_type(A.x.y) # N: Revealed type is "Literal[__main__.A.y]?"
2515 reveal_type(A.x.y.y) # N: Revealed type is "Literal[__main__.A.y]?"
2516 reveal_type(A.x.z) # N: Revealed type is "builtins.int"
2517
2518 reveal_type(A.y.x) # N: Revealed type is "Literal[__main__.A.x]?"
2519 reveal_type(A.y.y) # N: Revealed type is "Literal[__main__.A.y]?"
2520 reveal_type(A.y.z) # N: Revealed type is "builtins.int"
2521
2522 A.z.x # E: "int" has no attribute "x"
2523
2524 class B(Enum):
2525 x = 1
2526 value = 2
2527
2528 reveal_type(B.x) # N: Revealed type is "Literal[__main__.B.x]?"
2529 reveal_type(B.x.value) # N: Revealed type is "Literal[2]?"
2530 reveal_type(B.x.x.value) # N: Revealed type is "Literal[2]?"
2531 B.x.value.value # E: "int" has no attribute "value"
2532 B.x.value.value.value # E: "int" has no attribute "value"
2533 reveal_type(B.value) # N: Revealed type is "Literal[__main__.B.value]?"
2534 reveal_type(B.value.x) # N: Revealed type is "Literal[__main__.B.x]?"
2535 reveal_type(B.value.x.x) # N: Revealed type is "Literal[__main__.B.x]?"
2536 reveal_type(B.value.x.value) # N: Revealed type is "Literal[2]?"
2537 B.value.x.value.value # E: "int" has no attribute "value"
2538 B.value.value.value # E: "int" has no attribute "value"
2539 [builtins fixtures/dict.pyi]
2540
2541
2542 [case testErrorOnAnnotatedMember]
2543 from enum import Enum
2544
2545 class Medal(Enum):
2546 gold: int = 1 # E: Enum members must be left unannotated \
2547 # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members
2548 silver: str = 2 # E: Enum members must be left unannotated \
2549 # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \
2550 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
2551 bronze = 3
2552 [builtins fixtures/enum.pyi]
2553
2554 [case testEnumMemberWithPlaceholder]
2555 from enum import Enum
2556
2557 class Pet(Enum):
2558 CAT = ...
2559 DOG: str = ... # E: Enum members must be left unannotated \
2560 # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \
2561 # E: Incompatible types in assignment (expression has type "ellipsis", variable has type "str")
2562 [builtins fixtures/enum.pyi]
2563
2564 [case testEnumValueWithPlaceholderNodeType]
2565 # https://github.com/python/mypy/issues/11971
2566 from enum import Enum
2567 from typing import Any, Callable, Dict
2568 class Foo(Enum):
2569 Bar: Foo = Callable[[str], None] # E: Enum members must be left unannotated \
2570 # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \
2571 # E: Incompatible types in assignment (expression has type "<typing special form>", variable has type "Foo")
2572 Baz: Any = Callable[[Dict[str, "Missing"]], None] # E: Enum members must be left unannotated \
2573 # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \
2574 # E: Type application targets a non-generic function or class \
2575 # E: Name "Missing" is not defined
2576
2577 reveal_type(Foo.Bar) # N: Revealed type is "Literal[__main__.Foo.Bar]?"
2578 reveal_type(Foo.Bar.value) # N: Revealed type is "__main__.Foo"
2579 reveal_type(Foo.Baz) # N: Revealed type is "Literal[__main__.Foo.Baz]?"
2580 reveal_type(Foo.Baz.value) # N: Revealed type is "Any"
2581 [builtins fixtures/tuple.pyi]
2582 [typing fixtures/typing-full.pyi]
2583
2584
2585 [case testEnumWithOnlyImplicitMembersUsingAnnotationOnly]
2586 # flags: --warn-unreachable
2587 import enum
2588
2589
2590 class E(enum.IntEnum):
2591 A: int
2592 B: int
2593
2594
2595 def do_check(value: E) -> None:
2596 reveal_type(value) # N: Revealed type is "__main__.E"
2597 # this is a nonmember check, not an emum member check, and it should not narrow the value
2598 if value is E.A:
2599 return
2600
2601 reveal_type(value) # N: Revealed type is "__main__.E"
2602 "should be reachable"
2603
2604 [builtins fixtures/primitives.pyi]
2605 [typing fixtures/typing-full.pyi]
2606
2607 [case testStrEnumClassCorrectIterable]
2608 from enum import StrEnum
2609 from typing import Type, TypeVar
2610
2611 class Choices(StrEnum):
2612 LOREM = "lorem"
2613 IPSUM = "ipsum"
2614
2615 var = list(Choices)
2616 reveal_type(var) # N: Revealed type is "builtins.list[__main__.Choices]"
2617
2618 e: type[StrEnum]
2619 reveal_type(list(e)) # N: Revealed type is "builtins.list[enum.StrEnum]"
2620
2621 T = TypeVar("T", bound=StrEnum)
2622 def list_vals(e: Type[T]) -> list[T]:
2623 reveal_type(list(e)) # N: Revealed type is "builtins.list[T`-1]"
2624 return list(e)
2625
2626 reveal_type(list_vals(Choices)) # N: Revealed type is "builtins.list[__main__.Choices]"
2627 [builtins fixtures/enum.pyi]
2628
2629 [case testEnumAsClassMemberNoCrash]
2630 # https://github.com/python/mypy/issues/18736
2631 from enum import Enum
2632
2633 class Base:
2634 def __init__(self, namespace: tuple[str, ...]) -> None:
2635 # Not a bug: trigger defer
2636 names = [name for name in namespace if fail] # E: Name "fail" is not defined
2637 self.o = Enum("o", names) # E: Enum type as attribute is not supported \
2638 # E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members
2639 [builtins fixtures/tuple.pyi]
2640
2641 [case testSingleUnderscoreNameEnumMember]
2642 # flags: --warn-unreachable
2643
2644 # https://github.com/python/mypy/issues/19271
2645 from enum import Enum
2646
2647 class Things(Enum):
2648 _ = "under score"
2649
2650 def check(thing: Things) -> None:
2651 if thing is Things._:
2652 return None
2653 return None # E: Statement is unreachable
2654 [builtins fixtures/enum.pyi]
2655
2656 [case testSunderValueTypeEllipsis]
2657 from foo.bar import (
2658 Basic, FromStub, InheritedInt, InheritedStr, InheritedFlag,
2659 InheritedIntFlag, Wrapper
2660 )
2661
2662 reveal_type(Basic.FOO) # N: Revealed type is "Literal[foo.bar.Basic.FOO]?"
2663 reveal_type(Basic.FOO.value) # N: Revealed type is "Literal[1]?"
2664 reveal_type(Basic.FOO._value_) # N: Revealed type is "builtins.int"
2665
2666 reveal_type(FromStub.FOO) # N: Revealed type is "Literal[foo.bar.FromStub.FOO]?"
2667 reveal_type(FromStub.FOO.value) # N: Revealed type is "builtins.int"
2668 reveal_type(FromStub.FOO._value_) # N: Revealed type is "builtins.int"
2669
2670 reveal_type(Wrapper.Nested.FOO) # N: Revealed type is "Literal[foo.bar.Wrapper.Nested.FOO]?"
2671 reveal_type(Wrapper.Nested.FOO.value) # N: Revealed type is "builtins.int"
2672 reveal_type(Wrapper.Nested.FOO._value_) # N: Revealed type is "builtins.int"
2673
2674 reveal_type(InheritedInt.FOO) # N: Revealed type is "Literal[foo.bar.InheritedInt.FOO]?"
2675 reveal_type(InheritedInt.FOO.value) # N: Revealed type is "builtins.int"
2676 reveal_type(InheritedInt.FOO._value_) # N: Revealed type is "builtins.int"
2677
2678 reveal_type(InheritedStr.FOO) # N: Revealed type is "Literal[foo.bar.InheritedStr.FOO]?"
2679 reveal_type(InheritedStr.FOO.value) # N: Revealed type is "builtins.str"
2680 reveal_type(InheritedStr.FOO._value_) # N: Revealed type is "builtins.str"
2681
2682 reveal_type(InheritedFlag.FOO) # N: Revealed type is "Literal[foo.bar.InheritedFlag.FOO]?"
2683 reveal_type(InheritedFlag.FOO.value) # N: Revealed type is "builtins.int"
2684 reveal_type(InheritedFlag.FOO._value_) # N: Revealed type is "builtins.int"
2685
2686 reveal_type(InheritedIntFlag.FOO) # N: Revealed type is "Literal[foo.bar.InheritedIntFlag.FOO]?"
2687 reveal_type(InheritedIntFlag.FOO.value) # N: Revealed type is "builtins.int"
2688 reveal_type(InheritedIntFlag.FOO._value_) # N: Revealed type is "builtins.int"
2689
2690 [file foo/__init__.pyi]
2691 [file foo/bar/__init__.pyi]
2692 from enum import Enum, IntEnum, StrEnum, Flag, IntFlag
2693
2694 class Basic(Enum):
2695 _value_: int
2696 FOO = 1
2697
2698 class FromStub(Enum):
2699 _value_: int
2700 FOO = ...
2701
2702 class Wrapper:
2703 class Nested(Enum):
2704 _value_: int
2705 FOO = ...
2706
2707 class InheritedInt(IntEnum):
2708 FOO = ...
2709
2710 class InheritedStr(StrEnum):
2711 FOO = ...
2712
2713 class InheritedFlag(Flag):
2714 FOO = ...
2715
2716 class InheritedIntFlag(IntFlag):
2717 FOO = ...
2718 [builtins fixtures/enum.pyi]
2719
2720 [case testSunderValueTypeEllipsisNonStub]
2721 from enum import Enum, StrEnum
2722
2723 class Basic(Enum):
2724 _value_: int
2725 FOO = 1
2726
2727 reveal_type(Basic.FOO) # N: Revealed type is "Literal[__main__.Basic.FOO]?"
2728 reveal_type(Basic.FOO.value) # N: Revealed type is "Literal[1]?"
2729 reveal_type(Basic.FOO._value_) # N: Revealed type is "builtins.int"
2730
2731 # TODO: this and below should produce diagnostics, Ellipsis is not assignable to int
2732 # Now we do not check members against _value_ at all.
2733
2734 class FromStub(Enum):
2735 _value_: int
2736 FOO = ...
2737
2738 reveal_type(FromStub.FOO) # N: Revealed type is "Literal[__main__.FromStub.FOO]?"
2739 reveal_type(FromStub.FOO.value) # N: Revealed type is "builtins.ellipsis"
2740 reveal_type(FromStub.FOO._value_) # N: Revealed type is "builtins.int"
2741
2742 class InheritedStr(StrEnum):
2743 FOO = ...
2744
2745 reveal_type(InheritedStr.FOO) # N: Revealed type is "Literal[__main__.InheritedStr.FOO]?"
2746 reveal_type(InheritedStr.FOO.value) # N: Revealed type is "builtins.ellipsis"
2747 reveal_type(InheritedStr.FOO._value_) # N: Revealed type is "builtins.ellipsis"
2748
2749 class Wrapper:
2750 class Nested(StrEnum):
2751 FOO = ...
2752
2753 reveal_type(Wrapper.Nested.FOO) # N: Revealed type is "Literal[__main__.Wrapper.Nested.FOO]?"
2754 reveal_type(Wrapper.Nested.FOO.value) # N: Revealed type is "builtins.ellipsis"
2755 reveal_type(Wrapper.Nested.FOO._value_) # N: Revealed type is "builtins.ellipsis"
2756 [builtins fixtures/enum.pyi]
2757
2758 [case testStrEnumEqualityReachability]
2759 # flags: --strict-equality --warn-unreachable
2760
2761 from __future__ import annotations
2762 import enum
2763
2764 # https://github.com/python/mypy/issues/17162
2765
2766 class MyEnum(str, enum.Enum):
2767 A = 'a'
2768
2769 class MyEnum2(enum.StrEnum):
2770 A = 'a'
2771
2772 def f1():
2773 if MyEnum.A == 'a':
2774 1 + ''
2775
2776 if MyEnum2.A == 'a':
2777 1 + ''
2778 [builtins fixtures/primitives.pyi]
2779
2780 [case testStrEnumEqualityNarrowing]
2781 # flags: --strict-equality --warn-unreachable
2782
2783 from __future__ import annotations
2784 import enum
2785 from typing import Literal
2786
2787 # https://github.com/python/mypy/issues/18029
2788
2789 class Foo(enum.StrEnum):
2790 A = 'a'
2791
2792 def f1(a: Foo | Literal['foo']) -> Foo:
2793 if a == 'foo':
2794 # Ideally this is narrowed to just Literal['foo'] (if we learn to narrow based on enum value)
2795 reveal_type(a) # N: Revealed type is "__main__.Foo | Literal['foo']"
2796 return Foo.A
2797
2798 reveal_type(a) # N: Revealed type is "__main__.Foo"
2799 return a
2800 [builtins fixtures/primitives.pyi]
2801
2802 [case testStrEnumEqualityAlias]
2803 # flags: --strict-equality --warn-unreachable
2804 # https://github.com/python/mypy/issues/16830
2805 from __future__ import annotations
2806 from enum import Enum, auto
2807
2808 # https://github.com/python/mypy/issues/16830
2809
2810 class TrafficLight(Enum):
2811 RED = auto()
2812 AMBER = auto()
2813 GREEN = auto()
2814
2815 YELLOW = AMBER # alias
2816
2817 # Behaviour here is not yet ideal, because we don't model enum aliases
2818
2819 def demo1(inst: TrafficLight) -> None:
2820 if inst is TrafficLight.AMBER:
2821 reveal_type(inst) # N: Revealed type is "Literal[__main__.TrafficLight.AMBER]"
2822 else:
2823 reveal_type(inst) # N: Revealed type is "Literal[__main__.TrafficLight.RED] | Literal[__main__.TrafficLight.GREEN] | Literal[__main__.TrafficLight.YELLOW]"
2824
2825 if inst == TrafficLight.AMBER:
2826 reveal_type(inst) # N: Revealed type is "Literal[__main__.TrafficLight.AMBER]"
2827 else:
2828 reveal_type(inst) # N: Revealed type is "Literal[__main__.TrafficLight.RED] | Literal[__main__.TrafficLight.GREEN] | Literal[__main__.TrafficLight.YELLOW]"
2829
2830 def demo2() -> None:
2831 if TrafficLight.AMBER is TrafficLight.YELLOW: # E: Non-overlapping identity check (left operand type: "Literal[TrafficLight.AMBER]", right operand type: "Literal[TrafficLight.YELLOW]")
2832 1 + '' # E: Unsupported operand types for + ("int" and "str")
2833 else:
2834 1 + '' # E: Unsupported operand types for + ("int" and "str")
2835 [builtins fixtures/primitives.pyi]
2836
2837
2838 [case testEnumEqualityNarrowing]
2839 # flags: --strict-equality --warn-unreachable
2840
2841 from __future__ import annotations
2842 from typing import cast
2843 from enum import Enum, StrEnum
2844
2845 # https://github.com/python/mypy/issues/16830
2846
2847 class E(Enum):
2848 A = "a"
2849 B = "b"
2850 C = "c"
2851
2852 class Custom:
2853 def __eq__(self, other: object) -> bool: return True
2854
2855 class SE(StrEnum):
2856 A = "a"
2857 B = "b"
2858 C = "c"
2859
2860 def f1(x: int | str | E):
2861 if x == E.A:
2862 reveal_type(x) # N: Revealed type is "Literal[__main__.E.A]"
2863 else:
2864 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str | Literal[__main__.E.B] | Literal[__main__.E.C]"
2865
2866 if x in cast(list[E], []):
2867 reveal_type(x) # N: Revealed type is "__main__.E"
2868 else:
2869 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str | __main__.E"
2870
2871 if x == str():
2872 reveal_type(x) # N: Revealed type is "builtins.str"
2873 else:
2874 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str | __main__.E"
2875
2876 def f2(x: int | Custom | E):
2877 if x == E.A:
2878 reveal_type(x) # N: Revealed type is "__main__.Custom | Literal[__main__.E.A]"
2879 else:
2880 reveal_type(x) # N: Revealed type is "builtins.int | __main__.Custom | Literal[__main__.E.B] | Literal[__main__.E.C]"
2881
2882 if x in cast(list[E], []):
2883 reveal_type(x) # N: Revealed type is "__main__.Custom | __main__.E"
2884 else:
2885 reveal_type(x) # N: Revealed type is "builtins.int | __main__.Custom | __main__.E"
2886
2887 if x == str():
2888 reveal_type(x) # N: Revealed type is "__main__.Custom"
2889 else:
2890 reveal_type(x) # N: Revealed type is "builtins.int | __main__.Custom | __main__.E"
2891
2892 def f3_simple(x: str | SE):
2893 if x == SE.A:
2894 # Note the union gets simplified
2895 reveal_type(x) # N: Revealed type is "builtins.str"
2896 else:
2897 reveal_type(x) # N: Revealed type is "builtins.str"
2898
2899 def f3(x: int | str | SE):
2900 if x == SE.A:
2901 reveal_type(x) # N: Revealed type is "builtins.str"
2902 else:
2903 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
2904
2905 if x in cast(list[SE], []):
2906 reveal_type(x) # N: Revealed type is "builtins.str"
2907 else:
2908 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str | __main__.SE"
2909
2910 if x == str():
2911 reveal_type(x) # N: Revealed type is "builtins.str"
2912 else:
2913 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str | __main__.SE"
2914
2915 def f4(x: int | Custom | SE):
2916 if x == SE.A:
2917 reveal_type(x) # N: Revealed type is "__main__.Custom | Literal[__main__.SE.A]"
2918 else:
2919 reveal_type(x) # N: Revealed type is "builtins.int | __main__.Custom | Literal[__main__.SE.B] | Literal[__main__.SE.C]"
2920
2921 if x in cast(list[SE], []):
2922 reveal_type(x) # N: Revealed type is "__main__.Custom | __main__.SE"
2923 else:
2924 reveal_type(x) # N: Revealed type is "builtins.int | __main__.Custom | __main__.SE"
2925
2926 if x == str():
2927 reveal_type(x) # N: Revealed type is "__main__.Custom | __main__.SE"
2928 else:
2929 reveal_type(x) # N: Revealed type is "builtins.int | __main__.Custom | __main__.SE"
2930
2931 def f5(x: str | Custom | SE):
2932 if x == SE.A:
2933 reveal_type(x) # N: Revealed type is "builtins.str | __main__.Custom"
2934 else:
2935 reveal_type(x) # N: Revealed type is "builtins.str | __main__.Custom"
2936
2937 if x in cast(list[SE], []):
2938 reveal_type(x) # N: Revealed type is "builtins.str | __main__.Custom"
2939 else:
2940 reveal_type(x) # N: Revealed type is "builtins.str | __main__.Custom | __main__.SE"
2941
2942 if x == str():
2943 reveal_type(x) # N: Revealed type is "builtins.str | __main__.Custom"
2944 else:
2945 reveal_type(x) # N: Revealed type is "builtins.str | __main__.Custom | __main__.SE"
2946
2947 [builtins fixtures/primitives.pyi]
2948
2949
2950 [case testNarrowingWithIntEnumAndStrEnumUnionAmbiguous]
2951 # flags: --strict-equality --warn-unreachable
2952 from __future__ import annotations
2953 from enum import IntEnum, StrEnum
2954
2955 class IE(IntEnum):
2956 X = 1
2957 Y = 2
2958
2959 class SE(StrEnum):
2960 A = "a"
2961 B = "b"
2962
2963 def f(x: IE | SE) -> None:
2964 if x == IE.X:
2965 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.X]"
2966 else:
2967 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.Y] | __main__.SE"
2968 [builtins fixtures/primitives.pyi]
2969
2970
2971 [case testNarrowingWithStrEnumUnionNoneAmbiguous]
2972 # flags: --strict-equality --warn-unreachable
2973 from __future__ import annotations
2974 from enum import StrEnum
2975
2976 class SE(StrEnum):
2977 A = "a"
2978 B = "b"
2979
2980 def f(x: SE | None) -> None:
2981 if x == "a":
2982 reveal_type(x) # N: Revealed type is "__main__.SE"
2983 else:
2984 reveal_type(x) # N: Revealed type is "__main__.SE | None"
2985 [builtins fixtures/primitives.pyi]