A Python Enum is a special type of class. It inherits from the Enum class. The real name for an Enum is an Enumeration, but the name for an Enumeration can be shortened to Enum. The point of Enums is to provide an easy way to map an integer to a string in a special way. Some might say, “That sure sounds a whole lot like a dictionary”, but Enums are not the same as a dictionary. They have a few important differences.
Creating our own Python Enum:
Creating our own Python Enum starts with importing the Enum class from enum:
from enum import Enum
Now to create our own class. For this article, I am going to create an Enum called Fruit.
Now that I created the class, now it is time to create integer – value pairs. This is done by declaring constants (in reality just variables) inside the Enum class. See a screenshot of my code below:
You can now see how each of the five fruits are in essence variables with an integer assigned to each one. It is important that each variable has an unique value, but it is not important what value. Technically two values can be same, but that means a variable higher on the list of variables overrides variables lower on the list with the same name.
The next part of this article describes how to use an Python Enum.
Now that we have created an Enum class (in our case Fruit) we can now make a new object based on that class.
myfruit = Fruit(0)
This piece of code will make an object based on the Fruit class. Notice how we didn’t make an __init__ dunder method for this to work. The word dunder refers to the fact that there is a double underscore before and after the method name. In this case, the __init__ method is included in the inherited Enum class.
We can access the values of our newly created Fruit object by two methods. The first method is
.name. This method retrieves the variable name that is associated with the value we gave to the Fruit class object when we created it. In the case of our
myfruit object, the value that would be is returned is “Pear”. The second method is
.value. This method returns the value inputted when we created the Fruit Enum object, and the value in our example would be “0”. View the code snip below:
When this code is run, you can see it outputs the name of the fruit, the fruit name index, and the the object type. Notice how it is a
Fruit.Pear object, not a
That is all there is to Enums. A quick review of Enums: Create a new Enum class that inherits from the Enum class, define your terms in the new class, create a new object from the new Enum class, and utilize the Enum object with the special methods included in the Enum class.
Thanks for reading!