Skip to content

Commit 60371be

Browse files
committed
Enum now accepts String literals and final ...
values as 2nd arg. This aims to solve #8219
1 parent 8126091 commit 60371be

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

mypy/semanal_enum.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
)
1313
from mypy.semanal_shared import SemanticAnalyzerInterface
1414
from mypy.options import Options
15+
from mypy.types import get_proper_type, LiteralType
1516

1617

1718
class EnumCallAnalyzer:
@@ -146,6 +147,25 @@ def parse_enum_call_args(self, call: CallExpr,
146147
"%s() with dict literal requires string literals" % class_name, call)
147148
items.append(key.value)
148149
values.append(value)
150+
elif isinstance(args[1], RefExpr) and isinstance(args[1].node, Var):
151+
proper_type = get_proper_type(args[1].node.type)
152+
if (
153+
proper_type is not None
154+
and isinstance(proper_type, LiteralType)
155+
and isinstance(proper_type.value, str)
156+
):
157+
fields = proper_type.value
158+
for field in fields.replace(',', ' ').split():
159+
items.append(field)
160+
elif args[1].node.is_final and isinstance(args[1].node.final_value, str):
161+
fields = args[1].node.final_value
162+
for field in fields.replace(',', ' ').split():
163+
items.append(field)
164+
else:
165+
return self.fail_enum_call_arg(
166+
"%s() expects a string, tuple, list or dict literal as the second argument" %
167+
class_name,
168+
call)
149169
else:
150170
# TODO: Allow dict(x=1, y=2) as a substitute for {'x': 1, 'y': 2}?
151171
return self.fail_enum_call_arg(

test-data/unit/check-newsemanal.test

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2058,6 +2058,24 @@ from enum import Enum
20582058
A = Enum('A', ['x', 'y'])
20592059
A = Enum('A', ['z', 't']) # E: Name 'A' already defined on line 3
20602060

2061+
[case testNewAnalyzerEnumAcceptStringLiteral]
2062+
from enum import Enum
2063+
from typing_extensions import Literal
2064+
2065+
x: Literal['ANT BEE CAT DOG'] = 'ANT BEE CAT DOG'
2066+
Animal = Enum('Animal', x)
2067+
2068+
[builtins fixtures/tuple.pyi]
2069+
2070+
[case testNewAnalyzerEnumAcceptsFinalValue]
2071+
from enum import Enum
2072+
from typing_extensions import Final
2073+
2074+
x: Final['str'] = 'ANT BEE CAT DOG'
2075+
Animal = Enum('Animal', x)
2076+
2077+
[builtins fixtures/tuple.pyi]
2078+
20612079
[case testNewAnalyzerNewTypeRedefinition]
20622080
from typing import NewType
20632081

0 commit comments

Comments
 (0)