10.3. Enum StrEnum

  • List of finite choices

  • Enumerations with str values

  • StrEnum

10.3.1. StrEnum

>>> from enum import StrEnum
>>>
>>>
>>> class Color(StrEnum):
...     RED = 'red'
...     GREEN = 'green'
...     BLUE = 'blue'
>>>
>>>
>>> mycolor = Color.RED
>>>
>>> mycolor.name
'RED'
>>>
>>> mycolor.value
'red'

10.3.2. Auto

>>> from enum import StrEnum, auto
>>>
>>>
>>> class Color(StrEnum):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
>>>
>>>
>>> for color in Color:
...     print(color.name, color.value)
...
RED red
GREEN green
BLUE blue

10.3.3. Use Case - 1

>>> class Color(StrEnum):
...     RED = '#FF0000'
...     GREEN = '#00FF00'
...     BLUE = '#0000FF'

10.3.4. Use Case - 2

  • Dead or Alive

>>> class Status(StrEnum):
...     ALIVE = 'alive'
...     DEAD = 'dead'

10.3.5. Use Case - 3

>>> class Ordinal(StrEnum):
...     NORTH = 'N'
...     SOUTH = 'S'
...     EAST = 'E'
...     WEST = 'W'

10.3.6. Use Case - 4

>>> class Mood(StrEnum):
...     SAD = 'sad'
...     HAPPY = 'happy'

10.3.7. Use Case - 5

  • Issue Status

>>> class IssueStatus(StrEnum):
...     TODO = 'todo'
...     IN_PROGRESS = 'in-progress'
...     IN_REVIEW = 'in-review'
...     IN_TEST = 'in-test'
...     DONE = 'done'
...     REJECTED = 'rejected'

10.3.8. Use Case - 6

  • HTML Colors

>>> class Color(StrEnum):
...     AQUA = '#00FFFF'
...     BLACK = '#000000'
...     BLUE = '#0000FF'
...     FUCHSIA = '#FF00FF'
...     GRAY = '#808080'
...     GREEN = '#008000'
...     LIME = '#00FF00'
...     MAROON = '#800000'
...     NAVY = '#000080'
...     OLIVE = '#808000'
...     PINK = '#FF1A8C'
...     PURPLE = '#800080'
...     RED = '#FF0000'
...     SILVER = '#C0C0C0'
...     TEAL = '#008080'
...     WHITE = '#FFFFFF'
...     YELLOW = '#FFFF00'

10.3.9. Use Case - 7

>>> from dataclasses import dataclass
>>>
>>>
>>> class Role(StrEnum):
...     COMMANDER = 'CDT'
...     ENGINEER = 'ENG'
...     BOTANIST = 'BOT'
>>>
>>>
>>> @dataclass
... class Astronaut:
...     firstname: str
...     lastname: str
...     role: Role
>>>
>>>
>>> mark = Astronaut('Mark', 'Watney', role='not-existing')
>>> mark = Astronaut('Mark', 'Watney', role=Role.BOTANIST)

10.3.10. Use Case - 8

>>> 
... from django.db import models
...
... class HttpMethod(models.TextChoices):
...     GET = 'GET', _('GET')
...     POST = 'POST', _('POST')
...     PATCH = 'PATCH', _('PATCH')
...     PUT = 'PUT', _('PUT')
...     HEAD = 'HEAD', _('HEAD')
...     DELETE = 'DELETE', _('DELETE')
...     OPTIONS = 'OPTIONS', _('OPTIONS')
...     TRACE = 'TRACE', _('TRACE')
...     CONNECT = 'CONNECT', _('CONNECT')
...
...
... class Stage(models.TextChoices):
...     PRODUCTION = 'production', _('Production')
...     TEST = 'test', _('Test')