Sometimes, we want to represent an enum in Python.
In this article, we’ll look at how to represent an enum in Python.
How to represent an enum in Python?
To represent an enum in Python, we can use the enum
module.
For instance, we write:
from enum import Enum
class Animal(Enum):
ant = 1
bee = 2
cat = 3
dog = 4
print(Animal.ant)
We create the Animal
class that inherits from the Enum
class.
And we define the enum attributes inside the Animal
class.
Therefore, Animal.ant
is printed from the print
function.
Likewise, we can define an enum with the Enum
class directly by writing:
from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog')
print(Animal.ant)
We instantiate Enum
with the name of the enum and the enum attributes separated by spaces in a string.
So Animal.ant
is printed from the print
function.
Conclusion
To represent an enum in Python, we can use the enum
module.