Skip to content

Commit eec2cab

Browse files
committed
Prevent crash when enum call is stored into class attribute
1 parent 4fb187f commit eec2cab

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

mypy/semanal.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3464,8 +3464,8 @@ def record_special_form_lvalue(self, s: AssignmentStmt) -> None:
34643464
def analyze_enum_assign(self, s: AssignmentStmt) -> bool:
34653465
"""Check if s defines an Enum."""
34663466
if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, EnumCallExpr):
3467-
# Already analyzed enum -- nothing to do here.
3468-
return True
3467+
# Already analyzed enum -- only recheck that it can be stored correctly.
3468+
return len(s.lvalues) == 1 and isinstance(s.lvalues[0], NameExpr)
34693469
return self.enum_call_analyzer.process_enum_call(s, self.is_func_scope())
34703470

34713471
def analyze_namedtuple_assign(self, s: AssignmentStmt) -> bool:

test-data/unit/check-enum.test

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2512,3 +2512,15 @@ def list_vals(e: Type[T]) -> list[T]:
25122512

25132513
reveal_type(list_vals(Choices)) # N: Revealed type is "builtins.list[__main__.Choices]"
25142514
[builtins fixtures/enum.pyi]
2515+
2516+
[case testEnumAsClassMemberNoCrash]
2517+
# https://github.com/python/mypy/issues/18736
2518+
from enum import Enum
2519+
2520+
class Base:
2521+
def __init__(self, namespace: tuple[str, ...]) -> None:
2522+
# Not a bug: trigger defer
2523+
names = [name for name in namespace if fail] # E: Name "fail" is not defined
2524+
self.o = Enum("o", names) # E: Enum type as attribute is not supported \
2525+
# E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members
2526+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)