-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneric_enum.py
More file actions
58 lines (46 loc) · 1.52 KB
/
Copy pathgeneric_enum.py
File metadata and controls
58 lines (46 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from enum import Enum
from typing import Any, Self
class BaseEnum(Enum):
_label: str
def __new__(cls, *values: Any) -> Self:
"""
Called only at class-definition time with:
- (value,) → no label
- (value, label) → with label
Lookup at runtime (one-arg) never reaches here.
"""
if len(values) not in (1, 2):
raise TypeError(f"Invalid arguments for enum: {values!r}")
value: Any = values[0]
label: str = values[1] if len(values) == 2 else ""
if not isinstance(label, str):
raise TypeError(f"Enum label must be a string, not {label!r}")
member = object.__new__(cls)
member._value_, member._label = value, label
return member
def get_display(self) -> str:
return self._label
@property
def display(self) -> str:
return self._label
class Status(BaseEnum):
DRAFT = "draft", "Draft"
PUBLISHED = "published"
ARCHIVED = "archived", "Archived"
print(Status.__members__)
print(Status._member_map_)
print(Status._value2member_map_)
print(Status._member_names_)
print()
print(Status.DRAFT, Status.DRAFT.name, Status.DRAFT.value, Status.DRAFT.display, Status.DRAFT.get_display(), sep=", ")
print(Status("draft"), Status["DRAFT"], sep=", ")
print()
print(
Status.PUBLISHED,
Status.PUBLISHED.name,
Status.PUBLISHED.value,
Status.PUBLISHED.display,
Status.PUBLISHED.get_display(),
sep=", ",
)
print(Status("published"), Status["PUBLISHED"], sep=", ")