Tip 13 Enumerate Your Constants

Pythonic Programming — by Dmitry Zinoviev (21 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Avoid “Magic” Values | TOC | Chapter 2 General Tips 👉

★★3.4+ Another way to avoid “magic” values (Tip 12, Avoid “Magic” Values) is to add names not only to the variables that refer to them but also the values themselves. The mechanism is known as enumeration. It is implemented via the keyword enum in C/C++/Java. In Python, you import and subclass the class enum.Enum.

An enum-derived class is simply a collection of named constants (yes, true constants) that you can use anywhere in your code. For example, here is how to enumerate and later use the states of a typical traffic light:

​ ​class​ TrafficLightState(enum.Enum):
​ RED = 1
​ YELLOW = 2
​ GREEN = 3
​ OFF = 4
​ state = TrafficLightState.RED

The values assigned to the constants do not have to be an integer. They do not even have to be of the same data type, as long as they are distinct. If the actual values are not important, you can use the enum.auto method to generate them automatically.

​ ​class​ TrafficLightState(enum.Enum):
​ RED = enum.auto()
​ YELLOW = enum.auto()
​ GREEN = enum.auto()
​ OFF = enum.auto()

If needed, you can obtain the number of constants in an enum by measuring its “length” with len. You can also iterate through an enum and even transform it into a list, though the value of the latter transformation is…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.