Most modern programming languages support working with enumerations and Python is no exception. The programmer can do without them. However, like many other tools, enums in Python make it easier to write and edit code.
Table of Contents
What is enum in Python
Enum is a Python module, which literally translates to enumeration, thus reflecting the full essence of the module. Enums are a set of bounded, immutable values that can be assigned to a variable. For example:
- red = 1
- orange = 2
- yellow = 3
Connecting
The enum module is part of the standard Python 3 library, so you don’t need to install it separately, just connect the desired class using the import command:
from enum import enum
If for some reason the Python interpreter can not find the enum module, install it using
pip install enum
Creating
Enums are created using class syntax. This makes them easier to read and write. Example:
from enum import Enum class Sequences(Enum): # We create the class Sequences, the parent class list = 1 # of which is an Enum class tuple = 2 dict = 3 print(Sequences.list) # print the values print(Sequences.tuple.name) print(Sequences.dict.value)
As a result, we get the following:
Sequences.list tuple 3
The element values can be represented by any types (str, int, and others). The structure of the enumeration is as follows:
- The
Sequences
class is an enumeration. - The attributes
Sequences.list
,Sequences.tuple
and others are enum elements, which are functional constants. - The elements have names and values, the name of the
Sequences.list
element is “list” and the value is “3”. We refer to them withname
andvalue
, as when we output to the console in the example code shown above.
The programmer may not prescribe element values, instead he may use the auto() function, which automatically assigns a value of “1” to an element and one more to each subsequent one:
from enum import Enum, auto class Sequences(Enum): list = auto() # 1 tuple = auto() # 1 + 1 = 2 dict = auto() # 2 + 1 = 3
Properties
Iteration Support
Enumerations are iterable objects, which means that all elements can be iterated in a loop. Example:
from enum import Enum class Num(Enum): one = 1 two = 2 three = 3 for n in Num: print(n)
This will print the result to the console:
Num.one Num.two Num.three
Human-understandable semantics
One of the reasons why programmers prefer enumerations to arrays is because they are understandable.
The type of an enum element is an enum
This means that an enum is a type for all of its elements. That is, if a programmer creates an animals
enumeration with the elements: cat
, dog
, bird
. Then:
type(animals.cat) <enum 'animals'> type(animals.dog) <enum 'animals'> type(animals.bird) <enum 'animals'>
Hashability
Enum items are hashable. That is, the programmer can use them in dictionaries and sets. Recall that hash allows you to create high-performance structures, using hash functions to reduce the amount of data.
from enum import Enum class Color(Enum): BLUE = 1 BLACK = 2 BROWN = 3 apples = {} apples[Color.BLUE] = 'blue' apples[Color.BLACK] = 'black' print(apples)
Output:
{<Color.BLUE: 1>: 'blue', <Color.BLACK: 2>: 'black'}
Creating methods
The programmer can output an enumeration item entirely, either by displaying its name or by displaying its value. To simplify this, you can create a method on your own in the enumeration. Example:
from enum import Enum class Students(Enum): IGOR = 1 SERGEY = 2 VASYA = 3 def info(self): print("Name is %s, value is %s"%(self.name, self.value)) Students.IGOR.info() Name - IGOR, value - 1
Thus the output code is halved. Instead of writing Students.item.name
and Students.item.value
every time, the programmer just calls the info()
method. Note that this is just a small script with the enumeration of three items, in a large program this method can greatly reduce the code.
Common errors
When working with enumerations a programmer can make the following mistakes:
- You cannot use multiple elements with the same name, otherwise the interpreter will raise an exception.
- If you use the @unique decorator, the interpreter will raise an error if multiple enum elements have the same value.
- Enum elements do not support “>” or “<” comparison operations.
The programmer can create a subclass from an enumeration only if no elements are defined in it, otherwise the interpreter throws an exception.