Skip to content

Commit 3f7aba5

Browse files
elazargilevkivskyi
authored andcommitted
fix functional enum metaclass (#4942)
1 parent b4dbdd5 commit 3f7aba5

File tree

3 files changed

+18
-5
lines changed

3 files changed

+18
-5
lines changed

mypy/semanal_enum.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ def build_enum_call_typeinfo(self, name: str, items: List[str], fullname: str) -
8080
base = self.api.named_type_or_none(fullname)
8181
assert base is not None
8282
info = self.api.basic_new_typeinfo(name, base)
83+
info.metaclass_type = info.calculate_metaclass_type()
8384
info.is_enum = True
8485
for item in items:
8586
var = Var(item)

test-data/unit/check-enum.test

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,16 @@ x = y
392392
[out]
393393
main:8: error: Incompatible types in assignment (expression has type "__main__.B.E", variable has type "__main__.A.E")
394394

395+
[case testFunctionalEnumProtocols]
396+
from enum import IntEnum
397+
Color = IntEnum('Color', 'red green blue')
398+
reveal_type(Color['green']) # E: Revealed type is '__main__.Color'
399+
for c in Color:
400+
reveal_type(c) # E: Revealed type is '__main__.Color*'
401+
reveal_type(list(Color)) # E: Revealed type is 'builtins.list[__main__.Color*]'
402+
403+
[builtins fixtures/list.pyi]
404+
395405
[case testEnumWorkWithForward]
396406
from enum import Enum
397407
a: E = E.x

test-data/unit/lib-stub/enum.pyi

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
1-
from typing import Any, TypeVar, Union
1+
from typing import Any, TypeVar, Union, Type, Sized, Iterator, Mapping
22

3-
class EnumMeta(type):
4-
pass
3+
_T = TypeVar('_T')
4+
5+
class EnumMeta(type, Sized):
6+
def __iter__(self: Type[_T]) -> Iterator[_T]: pass
7+
def __reversed__(self: Type[_T]) -> Iterator[_T]: pass
8+
def __getitem__(self: Type[_T], name: str) -> _T: pass
59

610
class Enum(metaclass=EnumMeta):
711
def __new__(cls, value: Any) -> None: pass
@@ -17,8 +21,6 @@ class Enum(metaclass=EnumMeta):
1721
class IntEnum(int, Enum):
1822
value = 0 # type: int
1923

20-
_T = TypeVar('_T')
21-
2224
def unique(enumeration: _T) -> _T: pass
2325

2426
# In reality Flag and IntFlag are 3.6 only

0 commit comments

Comments
 (0)