Skip to content

Commit 7b4145d

Browse files
authored
fix referencing .value of a Choices variable (#2644)
1 parent bd3ca3c commit 7b4145d

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

mypy_django_plugin/transformers/choices.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from mypy.nodes import MemberExpr, NameExpr, TypeInfo
1+
from mypy.nodes import MemberExpr, NameExpr, TypeInfo, Var
22
from mypy.plugin import AttributeContext
33
from mypy.typeanal import make_optional_type
44
from mypy.types import AnyType, Instance, TupleType, TypeOfAny, get_proper_type
@@ -27,6 +27,12 @@ def transform_into_proper_attr_type(ctx: AttributeContext) -> MypyType:
2727

2828
if isinstance(expr, NameExpr) and isinstance(expr.node, TypeInfo):
2929
node = expr.node
30+
elif (
31+
isinstance(expr, NameExpr)
32+
and isinstance(expr.node, Var)
33+
and isinstance(var_node_type := get_proper_type(expr.node.type), Instance)
34+
):
35+
node = var_node_type.type
3036
else:
3137
ctx.api.fail("Unable to resolve type of choices property", ctx.context)
3238
return AnyType(TypeOfAny.from_error)

tests/assert_type/db/models/test_enums.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ class VoidChoices(BaseEmptyChoices):
7676
assert_type(Suit.CLUB.label, _StrOrPromise)
7777
assert_type(Suit.CLUB.value, int)
7878
assert_type(Suit.CLUB.do_not_call_in_templates, Literal[True])
79+
assert_type([e.value for e in Suit], list[int])
7980

8081
assert_type(YearInSchool.names, list[str])
8182
assert_type(YearInSchool.labels, list[_StrOrPromise])
@@ -97,6 +98,7 @@ class VoidChoices(BaseEmptyChoices):
9798
assert_type(Vehicle.CAR.value, int)
9899
assert_type(Vehicle.CAR.do_not_call_in_templates, Literal[True])
99100
assert_type(Vehicle.__empty__, _StrOrPromise)
101+
assert_type([e.value for e in Vehicle], list[int])
100102

101103
assert_type(Gender.names, list[str])
102104
assert_type(Gender.labels, list[_StrOrPromise])

0 commit comments

Comments
 (0)