To create an enumeration in Python, create a class that inherits from enum.Enum.
from enum import Enum
class Directions(Enum):
UP = 'i'
DOWN = 'm'
RIGHT = 'k'
LEFT = 'j'Enumerations contains constants called members. Each member has a name and a value. Access the value using dot notation or similar to a dictionary.
Directions['RIGHT']
<Directions.RIGHT: 'k'>or
Directions.RIGHT
<Directions.RIGHT: 'k'>To access just the value, add a .value:
Directions.RIGHT.value
'k'To access just the name of the member:
Directions.RIGHT.name
'RIGHT'There are other classes in the enum module the are designed for specific behavior.
- IntEnum: The members can be used anywhere you would use an
inttype. - StrEnum: The members can be used anywhere you would use a
strtype. - Flag: The members can be combines using Bitwise Operators.
Member values can be assigned automatically using auto() as the value in the class definition.