|
| 1 | +from typing import List, Literal, Tuple |
| 2 | + |
| 3 | +from django.db.models import IntegerChoices, TextChoices |
| 4 | +from django.utils.translation import gettext_lazy as _ |
| 5 | +from typing_extensions import assert_type |
| 6 | + |
| 7 | + |
| 8 | +class MyIntegerChoices(IntegerChoices): |
| 9 | + A = 1 |
| 10 | + B = 2, "B" |
| 11 | + C = 3, "B", "..." # pyright: ignore[reportCallIssue] |
| 12 | + D = 4, _("D") |
| 13 | + E = 5, 1 # pyright: ignore[reportArgumentType] |
| 14 | + F = "1" |
| 15 | + |
| 16 | + |
| 17 | +assert_type(MyIntegerChoices.A, Literal[MyIntegerChoices.A]) |
| 18 | +assert_type(MyIntegerChoices.A.label, str) |
| 19 | + |
| 20 | +# For standard enums, type checkers may infer the type of a member's value |
| 21 | +# (e.g. `MyIntegerChoices.A.value` inferred as `Literal[1]`). |
| 22 | +# However, Django choices metaclass is using the last value for the label. |
| 23 | +# Type checkers relies on the stub definition of the `value` property, typed |
| 24 | +# as `int`/`str` for `IntegerChoices`/`TextChoices`. |
| 25 | +assert_type(MyIntegerChoices.A.value, int) |
| 26 | + |
| 27 | + |
| 28 | +class MyTextChoices(TextChoices): |
| 29 | + A = "a" |
| 30 | + B = "b", "B" |
| 31 | + C = "c", _("C") |
| 32 | + D = 1 # pyright: ignore[reportArgumentType] |
| 33 | + E = "e", 1 # pyright: ignore[reportArgumentType] |
| 34 | + |
| 35 | + |
| 36 | +assert_type(MyTextChoices.A, Literal[MyTextChoices.A]) |
| 37 | +assert_type(MyTextChoices.A.label, str) |
| 38 | +assert_type(MyTextChoices.A.value, str) |
| 39 | + |
| 40 | + |
| 41 | +# Assertions related to the metaclass: |
| 42 | + |
| 43 | +assert_type(MyIntegerChoices.values, List[int]) |
| 44 | +assert_type(MyIntegerChoices.choices, List[Tuple[int, str]]) |
| 45 | +assert_type(MyTextChoices.values, List[str]) |
| 46 | +assert_type(MyTextChoices.choices, List[Tuple[str, str]]) |
0 commit comments