Skip to content

Latest commit

 

History

History
56 lines (39 loc) · 1.13 KB

File metadata and controls

56 lines (39 loc) · 1.13 KB

Create Enumeration In Python

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 int type.
  • StrEnum: The members can be used anywhere you would use a str type.
  • Flag: The members can be combines using Bitwise Operators.

Member values can be assigned automatically using auto() as the value in the class definition.

References