Sub topic 1
Defining your first Enum
Prerequisites
This chapter assumes you can read and write a Python class, and you know that class attributes are shared by the class. It also assumes you know the difference between == and is. You need Python 3.8 or later. Later chapters mention a few features that need newer versions, and they say so where it matters.
Why an enumeration
Programs often need a small, fixed set of choices: traffic light colors, order states, log levels. A common first attempt is a set of module-level constants:
RED = 1
GREEN = 2
BLUE = 3
print(RED) # 1
print(RED == 1) # True
print(RED + BLUE) # 4, which has no meaning for colorsThis works, but the constants are only integers. Printing one gives a bare number. Any integer passes for a color, and arithmetic on colors runs without complaint. Nothing groups the names together.
An enumeration (enum) is a set of named, constant values defined as one type. Python provides this in the standard enum module. Each named value is called a member.
The basic definition
To define an enum, subclass Enum and list the members as class attributes:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED) # Color.RED
print(repr(Color.RED)) # <Color.RED: 1>
print(Color.RED.name) # RED
print(Color.RED.value) # 1Three details are worth noting.
Color.REDis not the integer1. It is an object of typeColorthat carries the nameREDand the value1.- The printed form includes the class name, so output and logs are self-describing.
- Member names are conventionally written in uppercase, like constants.
The right-hand side of each assignment is the member's value. Values are often integers or strings, but any object works.
What the class does for you
When Python executes the class body, the Enum machinery replaces each plain attribute with a member object. It creates exactly one object per member, and the class holds them. This is why the same member is always the same object.
Because members are real objects of the enum type, you can check what kind of thing you hold:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(isinstance(Color.RED, Color)) # True
print(isinstance(1, Color)) # False
print(Color.RED == 1) # FalseThe last line surprises many people. A plain Enum member never equals its raw value. This protects you from mixing colors with numbers by accident. Later chapters cover IntEnum and StrEnum, which relax this rule on purpose.
Members are constants
Once the class exists, you cannot rebind its members:
from enum import Enum
class Color(Enum):
RED = 1
try:
Color.RED = 5
except AttributeError as error:
print("cannot reassign:", error)Python raises AttributeError, so a typo or a careless assignment cannot silently change what Color.RED means.
A common mistake
An enum class is a type, so do not call it to create a new member. Color(4) does not make a fourth color. It looks up an existing member by value and raises ValueError if none matches. The next chapter covers lookups in detail. To add a member, edit the class definition.
Exercise
Given class Light(Enum) with STOP = "red" and GO = "green", what do Light.STOP == "red" and isinstance(Light.STOP, Light) evaluate to, and why?
Show answer
The first is False and the second is True. Light.STOP is a member object of type Light, not the string "red". A plain Enum member does not equal its raw value, but it is an instance of its enum class. The string is available as Light.STOP.value.