Skip to content

Instantly share code, notes, and snippets.

@duTianze
Last active December 8, 2023 06:58
Show Gist options
  • Save duTianze/ec16ab6658e293ab2b1db3b02876763a to your computer and use it in GitHub Desktop.
Save duTianze/ec16ab6658e293ab2b1db3b02876763a to your computer and use it in GitHub Desktop.
python enum with label
from enum import IntEnum
from pydantic import BaseModel
class DropdownCode(BaseModel):
display_code: Optional[str] = Field(None, title="表示コード")
display_name: Optional[str] = Field(None, title="表示名")
class LabelEnum(IntEnum):
def __new__(cls, value, label):
obj = int.__new__(cls, value)
obj._value_ = value
obj.label = label
return obj
@classmethod
def to_label(cls, code: int) -> Union[str, None]:
if code is None:
return None
return cls(code).labe
@classmethod
def parse_options(cls) -> List[DropdownCode]:
options = []
for member in cls:
options.append(DropdownCode(display_code=str(member.value), display_name=member.label))
return options
class EmailNotifyEnabled(LabelEnum):
DISABLE = (0, 'しない')
ENABLE = (1, 'する')
EmailNotifyEnabled.DISABLE.label
>> 'しない'
EmailNotifyEnabled(1).label
>> 'する'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment