Skip to content

Commit 195f758

Browse files
committed
disallow generic Enums and fix assigning Enum indexes
Fixes python#3137
1 parent 72565f0 commit 195f758

3 files changed

Lines changed: 36 additions & 0 deletions

File tree

‎mypy/semanal.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1016,6 +1016,8 @@ def analyze_base_classes(self, defn: ClassDef) -> None:
10161016
# the MRO. Fix MRO if needed.
10171017
if info.mro and info.mro[-1].fullname() != 'builtins.object':
10181018
info.mro.append(self.object_type().type)
1019+
if defn.info.is_enum and defn.type_vars:
1020+
self.fail("Enum class cannot be generic", defn)
10191021

10201022
def expr_to_analyzed_type(self, expr: Expression) -> Type:
10211023
if isinstance(expr, CallExpr):

‎mypy/typeanal.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ def analyze_type_alias(node: Expression,
6161
base.fullname in type_constructors or
6262
base.kind == TYPE_ALIAS):
6363
return None
64+
# Enums can't be generic, and without this check we may incorrectly interpret indexing
65+
# an Enum class as creating a type alias.
66+
if isinstance(base.node, TypeInfo) and base.node.is_enum:
67+
return None
6468
else:
6569
return None
6670
else:

‎test-data/unit/check-enum.test‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,36 @@ E[1]
154154
[out]
155155
main:4: error: Enum index should be a string (actual index type "int")
156156

157+
158+
[case testEnumIndexIsNotAnAlias]
159+
from enum import Enum
160+
161+
class E(Enum):
162+
a = 1
163+
b = 2
164+
reveal_type(E['a']) # E: Revealed type is '__main__.E'
165+
E['a']
166+
x = E['a']
167+
reveal_type(x) # E: Revealed type is '__main__.E'
168+
169+
def get_member(name: str) -> E:
170+
val = E[name]
171+
return val
172+
173+
reveal_type(get_member('a')) # E: Revealed type is '__main__.E'
174+
175+
[case testGenericEnum]
176+
from enum import Enum
177+
from typing import Generic, TypeVar
178+
179+
T = TypeVar('T')
180+
181+
class F(Generic[T], Enum): # E: Enum class cannot be generic
182+
x: T
183+
y: T
184+
185+
reveal_type(F[int].x) # E: Revealed type is '__main__.F[builtins.int*]'
186+
157187
[case testEnumFlag]
158188
from enum import Flag
159189
class C(Flag):

0 commit comments

Comments
 (0)