Skip to content

Adds check for unique enum keys #11267

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
Oct 8, 2021
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
7 changes: 7 additions & 0 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -2748,6 +2748,13 @@ def analyze_name_lvalue(self,
existing = names.get(name)

outer = self.is_global_or_nonlocal(name)
if kind == MDEF and isinstance(self.type, TypeInfo) and self.type.is_enum:
# Special case: we need to be sure that `Enum` keys are unique.
if existing:
self.fail('Attempted to reuse member name "{}" in Enum definition "{}"'.format(
name, self.type.name,
), lvalue)

if (not existing or isinstance(existing.node, PlaceholderNode)) and not outer:
# Define new variable.
var = self.make_name_lvalue_var(lvalue, kind, not explicit_type)
Expand Down
31 changes: 31 additions & 0 deletions test-data/unit/check-enum.test
Original file line number Diff line number Diff line change
Expand Up @@ -1360,3 +1360,34 @@ class E(IntEnum):
A = N(0)

reveal_type(E.A.value) # N: Revealed type is "__main__.N"


[case testEnumReusedKeys]
# https://github.com/python/mypy/issues/11248
from enum import Enum
class Correct(Enum):
x = 'y'
y = 'x'
class Foo(Enum):
A = 1
A = 'a' # E: Attempted to reuse member name "A" in Enum definition "Foo" \
# E: Incompatible types in assignment (expression has type "str", variable has type "int")
reveal_type(Foo.A.value) # N: Revealed type is "builtins.int"

class Bar(Enum):
A = 1
B = A = 2 # E: Attempted to reuse member name "A" in Enum definition "Bar"
class Baz(Enum):
A = 1
B, A = (1, 2) # E: Attempted to reuse member name "A" in Enum definition "Baz"
[builtins fixtures/tuple.pyi]

[case testEnumReusedKeysOverlapWithLocalVar]
from enum import Enum
x = 1
class Foo(Enum):
x = 2
def method(self) -> None:
x = 3
x = 4
[builtins fixtures/bool.pyi]