Skip to content

disallow generic Enums and fix assigning Enum indexes #3140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1016,6 +1016,8 @@ def analyze_base_classes(self, defn: ClassDef) -> None:
# the MRO. Fix MRO if needed.
if info.mro and info.mro[-1].fullname() != 'builtins.object':
info.mro.append(self.object_type().type)
if defn.info.is_enum and defn.type_vars:
self.fail("Enum class cannot be generic", defn)

def expr_to_analyzed_type(self, expr: Expression) -> Type:
if isinstance(expr, CallExpr):
Expand Down
4 changes: 4 additions & 0 deletions mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ def analyze_type_alias(node: Expression,
base.fullname in type_constructors or
base.kind == TYPE_ALIAS):
return None
# Enums can't be generic, and without this check we may incorrectly interpret indexing
# an Enum class as creating a type alias.
if isinstance(base.node, TypeInfo) and base.node.is_enum:
return None
else:
return None
else:
Expand Down
34 changes: 31 additions & 3 deletions test-data/unit/check-enum.test
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,37 @@ main:5: error: Revealed type is '__main__.E'
from enum import IntEnum
class E(IntEnum):
a = 1
E[1]
[out]
main:4: error: Enum index should be a string (actual index type "int")
E[1] # E: Enum index should be a string (actual index type "int")
x = E[1] # E: Enum index should be a string (actual index type "int")

[case testEnumIndexIsNotAnAlias]
from enum import Enum

class E(Enum):
a = 1
b = 2
reveal_type(E['a']) # E: Revealed type is '__main__.E'
E['a']
x = E['a']
reveal_type(x) # E: Revealed type is '__main__.E'

def get_member(name: str) -> E:
val = E[name]
return val

reveal_type(get_member('a')) # E: Revealed type is '__main__.E'

[case testGenericEnum]
from enum import Enum
from typing import Generic, TypeVar

T = TypeVar('T')

class F(Generic[T], Enum): # E: Enum class cannot be generic
x: T
y: T

reveal_type(F[int].x) # E: Revealed type is '__main__.F[builtins.int*]'

[case testEnumFlag]
from enum import Flag
Expand Down