Skip to content

Commit

Permalink
Class property Choices.values returns list of Members (#232)
Browse files Browse the repository at this point in the history
For any subclass `E` of `Choices`, `IntegerChoices` or `TextChoices` `E.values` now has type `Sequence[E]` instead of `list[str]` (or `list[int]`). Similarly for `E.choices`. The implementation is borrowed from the typeshed implementation of `enum.EnumMeta`.

I’m not sure about the tests, i.e. just putting a subclass of `Choices` into the models module. Happy to change that.
  • Loading branch information
geigerzaehler authored Apr 3, 2024
1 parent 7e36372 commit 8508231
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 19 deletions.
28 changes: 9 additions & 19 deletions django-stubs/db/models/enums.pyi
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import enum
from typing import Any
from typing import Any, Sequence, TypeVar

_EnumMemberT = TypeVar("_EnumMemberT")

class ChoicesMeta(enum.EnumMeta):
names: list[str] = ...
choices: list[tuple[Any, str]] = ...
labels: list[str] = ...
values: list[Any] = ...
def __contains__(self, item: Any) -> bool: ...
@property
def values(self: type[_EnumMemberT]) -> Sequence[_EnumMemberT]: ...
@property
def choices(self: type[_EnumMemberT]) -> Sequence[tuple[_EnumMemberT, str]]: ...

class Choices(enum.Enum, metaclass=ChoicesMeta):
def __str__(self) -> Any: ...
Expand All @@ -15,24 +19,10 @@ class Choices(enum.Enum, metaclass=ChoicesMeta):
@property
def value(self) -> Any: ...

# fake
class _IntegerChoicesMeta(ChoicesMeta):
names: list[str] = ...
choices: list[tuple[int, str]] = ...
labels: list[str] = ...
values: list[int] = ...

class IntegerChoices(int, Choices, metaclass=_IntegerChoicesMeta):
class IntegerChoices(int, Choices):
@property
def value(self) -> int: ...

# fake
class _TextChoicesMeta(ChoicesMeta):
names: list[str] = ...
choices: list[tuple[str, str]] = ...
labels: list[str] = ...
values: list[str] = ...

class TextChoices(str, Choices, metaclass=_TextChoicesMeta):
class TextChoices(str, Choices):
@property
def value(self) -> str: ...
22 changes: 22 additions & 0 deletions tests/trout/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,28 @@
from psycopg2.extras import execute_values


class CustomChoices(models.enums.Choices):
A = "B", "A"

def go(self) -> None:
pass


CustomChoices.values[0].go()
CustomChoices.choices[0][0].go()


class CustomIntegerChoices(models.enums.IntegerChoices):
A = 1, "A"

def go(self) -> None:
pass


CustomIntegerChoices.values[0].go()
CustomIntegerChoices.choices[0][0].go()


class User(models.Model):
pass

Expand Down

0 comments on commit 8508231

Please sign in to comment.