| 1 |
import enum |
| 2 |
import warnings |
| 3 |
|
| 4 |
from django.utils.deprecation import RemovedInDjango60Warning |
| 5 |
from django.utils.functional import Promise |
| 6 |
from django.utils.version import PY311, PY312 |
| 7 |
|
| 8 |
if PY311: |
| 9 |
from enum import EnumType, IntEnum, StrEnum |
| 10 |
from enum import property as enum_property |
| 11 |
else: |
| 12 |
from enum import EnumMeta as EnumType |
| 13 |
from types import DynamicClassAttribute as enum_property |
| 14 |
|
| 15 |
class ReprEnum(enum.Enum): |
| 16 |
def __str__(self): |
| 17 |
return str(self.value) |
| 18 |
|
| 19 |
class IntEnum(int, ReprEnum): |
| 20 |
pass |
| 21 |
|
| 22 |
class StrEnum(str, ReprEnum): |
| 23 |
pass |
| 24 |
|
| 25 |
|
| 26 |
__all__ = ["Choices", "IntegerChoices", "TextChoices"] |
| 27 |
|
| 28 |
|
| 29 |
class ChoicesType(EnumType): |
| 30 |
"""A metaclass for creating a enum choices.""" |
| 31 |
|
| 32 |
def __new__(metacls, classname, bases, classdict, **kwds): |
| 33 |
labels = [] |
| 34 |
for key in classdict._member_names: |
| 35 |
value = classdict[key] |
| 36 |
if ( |
| 37 |
isinstance(value, (list, tuple)) |
| 38 |
and len(value) > 1 |
| 39 |
and isinstance(value[-1], (Promise, str)) |
| 40 |
): |
| 41 |
*value, label = value |
| 42 |
value = tuple(value) |
| 43 |
else: |
| 44 |
label = key.replace("_", " ").title() |
| 45 |
labels.append(label) |
| 46 |
# Use dict.__setitem__() to suppress defenses against double |
| 47 |
# assignment in enum's classdict. |
| 48 |
dict.__setitem__(classdict, key, value) |
| 49 |
cls = super().__new__(metacls, classname, bases, classdict, **kwds) |
| 50 |
for member, label in zip(cls.__members__.values(), labels): |
| 51 |
member._label_ = label |
| 52 |
return enum.unique(cls) |
| 53 |
|
| 54 |
if not PY312: |
| 55 |
|
| 56 |
def __contains__(cls, member): |
| 57 |
if not isinstance(member, enum.Enum): |
| 58 |
# Allow non-enums to match against member values. |
| 59 |
return any(x.value == member for x in cls) |
| 60 |
return super().__contains__(member) |
| 61 |
|
| 62 |
@property |
| 63 |
def names(cls): |
| 64 |
empty = ["__empty__"] if hasattr(cls, "__empty__") else [] |
| 65 |
return empty + [member.name for member in cls] |
| 66 |
|
| 67 |
@property |
| 68 |
def choices(cls): |
| 69 |
empty = [(None, cls.__empty__)] if hasattr(cls, "__empty__") else [] |
| 70 |
return empty + [(member.value, member.label) for member in cls] |
| 71 |
|
| 72 |
@property |
| 73 |
def labels(cls): |
| 74 |
return [label for _, label in cls.choices] |
| 75 |
|
| 76 |
@property |
| 77 |
def values(cls): |
| 78 |
return [value for value, _ in cls.choices] |
| 79 |
|
| 80 |
|
| 81 |
class Choices(enum.Enum, metaclass=ChoicesType): |
| 82 |
"""Class for creating enumerated choices.""" |
| 83 |
|
| 84 |
if PY311: |
| 85 |
do_not_call_in_templates = enum.nonmember(True) |
| 86 |
else: |
| 87 |
|
| 88 |
@property |
| 89 |
def do_not_call_in_templates(self): |
| 90 |
return True |
| 91 |
|
| 92 |
@enum_property |
| 93 |
def label(self): |
| 94 |
return self._label_ |
| 95 |
|
| 96 |
# A similar format was proposed for Python 3.10. |
| 97 |
def __repr__(self): |
| 98 |
return f"{self.__class__.__qualname__}.{self._name_}" |
| 99 |
|
| 100 |
|
| 101 |
class IntegerChoices(Choices, IntEnum): |
| 102 |
"""Class for creating enumerated integer choices.""" |
| 103 |
|
| 104 |
pass |
| 105 |
|
| 106 |
|
| 107 |
class TextChoices(Choices, StrEnum): |
| 108 |
"""Class for creating enumerated string choices.""" |
| 109 |
|
| 110 |
@staticmethod |
| 111 |
def _generate_next_value_(name, start, count, last_values): |
| 112 |
return name |
| 113 |
|
| 114 |
|
| 115 |
def __getattr__(name): |
| 116 |
if name == "ChoicesMeta": |
| 117 |
warnings.warn( |
| 118 |
"ChoicesMeta is deprecated in favor of ChoicesType.", |
| 119 |
RemovedInDjango60Warning, |
| 120 |
stacklevel=2, |
| 121 |
) |
| 122 |
return ChoicesType |
| 123 |
raise AttributeError(f"module {__name__!r} has no attribute {name!r}") |