How can I represent an 'Enum' in Python?
In Python, you can represent an Enum (enumeration) by using the enum
module or by creating a class that inherits from enum.Enum
. To use the enum
module, you can define your enumeration using the Enum
class like this:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
Watch a video course
Python - The Practical Guide
You can also define the Enum values directly with the Enum() function
from enum import Enum
Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])
Once you've defined your enumeration, you can access the enumeration values using the name of the enumeration and the value, like this:
from enum import Enum
Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])
print(Color.RED)
You can also loop through all the values in the enumeration:
from enum import Enum
Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])
for color in Color:
print(color)
Additionally you can use the value
and name
attributes of the enumerated values to access the name and value of each enumerated value respectively.
from enum import Enum
Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])
print(Color.RED.name) # prints 'RED'
print(Color.RED.value) # prints 1