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.
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:
Enums in Python using the enum.Enum class
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
You can also define the Enum values directly with the Enum() function
Enums in Python using 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:
Access enumeration values in Python
from enum import Enum
Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])
print(Color.RED)You can also loop through all the values in the enumeration:
Loop through all the values in an enumeration in Python
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.
Using name and value attributes of the enumerated values in Python
from enum import Enum
Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])
print(Color.RED.name) # prints 'RED'
print(Color.RED.value) # prints 1