Python Enums
What you will learn
- Why magic strings and numbers are risky, and what an enum is
- Members,
nameandvalue - Lookup, iteration and comparison
IntEnum,auto(),Flagand@unique- Methods and extra data on members
- Using enums with
matchand JSON
1. The problem with magic values
Programs often need a fixed set of choices: order status, colours, directions. Beginners use strings or numbers:
status = "shiped" # a typo, and nothing complains
A misspelled string is just another string, so the bug hides until much later. An enumeration (enum) is a class whose objects are a fixed list of named constants. Typos become errors, and the choices are listed in one place.
2. Defining an enum
Inherit from Enum (module enum) and list the members as class attributes:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED)
print(repr(Color.RED))
print(Color.RED.name, Color.RED.value)
print(type(Color.RED))
Color.RED
<Color.RED: 1>
RED 1
<enum 'Color'>
RED,GREENandBLUEare the members. Each is an object of the classColor(not anint).- Every member has a
name(a string) and avalue. - By convention, member names are in
UPPER_CASE(lesson 2.3).
Quick check: what are `Color.GREEN.name` and `Color.GREEN.value`?
'GREEN' and 2.
3. Looking up members
print(Color(2)) # by value
print(Color["BLUE"]) # by name
print(list(Color))
print(len(Color), Color.RED in Color)
Color.GREEN
Color.BLUE
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
3 True
Bad lookups fail loudly:
Color(9)
Color["PINK"]
ValueError: 9 is not a valid Color
KeyError: 'PINK'
You can loop over an enum, in definition order:
for c in Color:
print(c.name, c.value)
RED 1
GREEN 2
BLUE 3
Color.__members__ is a read-only mapping of names to members.
4. Comparing members
Members are singletons: there is exactly one Color.RED. Compare them with == or is. They are not equal to their values, and they cannot be ordered:
print(Color.RED == Color.RED, Color.RED is Color.RED)
print(Color.RED == 1, Color.RED is Color(1))
Color.RED < Color.BLUE
True True
False True
TypeError: '<' not supported between instances of 'Color' and 'Color'
Members are also constants: you cannot reassign them.
Color.RED = 5
AttributeError: cannot reassign member 'RED'
Members are hashable, so they work as dictionary keys: {Status.ACTIVE: 1}.
5. String values and aliases
Values need not be numbers. Strings are common, especially when the value is stored in a file or database:
class Status(Enum):
ACTIVE = "active"
DONE = "done"
print(Status("done"), Status.DONE.value)
Status.DONE done
If two names have the same value, the second is an alias of the first:
class Dup(Enum):
A = 1
B = 1
print(Dup.B, Dup.A is Dup.B, list(Dup))
Dup.A True [<Dup.A: 1>]
To forbid aliases, add the @unique decorator:
from enum import unique
@unique
class D2(Enum):
A = 1
B = 1
ValueError: duplicate values found in <enum 'D2'>: B -> A
6. auto, IntEnum and Flag
auto() picks the values (1, 2, 3, ...) when you do not care what they are:
from enum import auto
class Dir(Enum):
N = auto()
S = auto()
print(list(Dir), Dir.S.value)
[<Dir.N: 1>, <Dir.S: 2>] 2
IntEnum members are integers, so they compare and calculate like numbers (useful for levels or when talking to code that wants ints):
from enum import IntEnum
class Level(IntEnum):
LOW = 1
HIGH = 3
print(Level.LOW < Level.HIGH, Level.HIGH == 3, Level.HIGH + 1)
print(sorted([Level.HIGH, Level.LOW]), int(Level.HIGH))
True True 4
[<Level.LOW: 1>, <Level.HIGH: 3>] 3
The price: an IntEnum also equals plain ints and mixes with unrelated numbers, which weakens the "typed choice" safety. Use a plain Enum unless you need the numbers.
Flag members can be combined with | and tested with in. Use powers of two as values (lesson 3.7):
from enum import Flag
class Perm(Flag):
R = 4
W = 2
X = 1
rw = Perm.R | Perm.W
print(rw)
print(Perm.R in rw, Perm.X in rw, rw.value)
print(Perm(7), bool(Perm(0)))
Perm.R|W
True False 6
Perm.R|W|X False
7. Methods and extra data
An enum is a class, so members can have methods, properties and class methods, and each can carry several values through __init__:
class Planet(Enum):
EARTH = (5.97e24, 6.37e6)
MARS = (6.42e23, 3.39e6)
def __init__(self, mass, radius):
self.mass, self.radius = mass, radius
@property
def gravity(self):
return round(6.674e-11 * self.mass / self.radius ** 2, 2)
print(Planet.EARTH.gravity, Planet.MARS.gravity)
9.82 3.73
(The values are rounded textbook figures.) A class method makes a friendly parser:
class Shape(Enum):
CIRCLE = "circle"
SQUARE = "square"
def describe(self):
return f"A {self.value}"
@classmethod
def parse(cls, text):
return cls(text.strip().lower())
print(Shape.parse(" Circle ").describe())
A circle
8. Enums with match, text and JSON
Enums pair well with match (lesson 5.5), using the dotted names:
def paint(c: Color):
match c:
case Color.RED:
return "stop"
case Color.GREEN:
return "go"
case _:
return "other"
print(paint(Color.RED), paint(Color.BLUE))
stop other
For printing, use .name or .value explicitly:
print(f"{Color.RED}", f"{Color.RED.name}", str(Status.DONE))
Color.RED RED Status.DONE
For JSON (lesson 15.7), save the value, not the member; json cannot encode a plain Enum:
import json
print(json.dumps({"s": Status.DONE.value}))
{"s": "done"}
(An IntEnum member is an int, so json.dumps writes its number.)
9. When to use an enum
| Use an enum for | Do not use it for |
|---|---|
| a fixed set of named choices (status, colour, role, direction) | values that are open-ended (names, amounts) |
| options passed to functions, instead of strings | a set that changes while the program runs |
| states of a workflow | a simple on/off (use bool) |
Worked example: order status with allowed moves
An order moves through states, but only along allowed paths. The enum lists the states, a table lists the moves, and a parser turns user text into a status with a helpful error.
from enum import Enum
class Status(Enum):
NEW = "new"
PAID = "paid"
SHIPPED = "shipped"
CANCELLED = "cancelled"
@property
def next_states(self):
return TRANSITIONS[self]
@classmethod
def parse(cls, text):
try:
return cls(text.strip().lower())
except ValueError:
allowed = ", ".join(s.value for s in cls)
raise ValueError(f"unknown status {text!r}; use one of: {allowed}") from None
TRANSITIONS = {
Status.NEW: (Status.PAID, Status.CANCELLED),
Status.PAID: (Status.SHIPPED, Status.CANCELLED),
Status.SHIPPED: (),
Status.CANCELLED: (),
}
class Order:
def __init__(self):
self.status = Status.NEW
def move(self, new):
new = Status.parse(new) if isinstance(new, str) else new
if new not in self.status.next_states:
raise ValueError(f"cannot go from {self.status.value} to {new.value}")
self.status = new
return self
o = Order()
print(o.status)
o.move("paid")
print(o.status, [s.value for s in o.status.next_states])
o.move(Status.SHIPPED)
print(o.status)
for bad in ("new", "lost"):
try:
o.move(bad)
except ValueError as e:
print("ValueError:", e)
Status.NEW
Status.PAID ['shipped', 'cancelled']
Status.SHIPPED
ValueError: cannot go from shipped to new
ValueError: unknown status 'lost'; use one of: new, paid, shipped, cancelled
| Idea | Where |
|---|---|
| a fixed set of states | the Status members |
| a property and a class method on the enum | next_states and parse |
| a dictionary keyed by members | TRANSITIONS |
| friendly errors | parse re-raises with the allowed values (from None hides the inner error) |
| no typos | Status.SHIPED would fail immediately with AttributeError |
The states are made up for the lesson.
Common mistakes
- Comparing a member with its value (
Color.RED == 1isFalse; useColor.RED.value == 1orColor(1) is Color.RED). - Trying to order plain enum members (use
IntEnumor compare values). - Forgetting aliases when two names share a value.
- Using an
IntEnumwhere a plainEnumwould be safer. - Passing members to
json.dumps(store.value). - Changing members (not allowed).
Key takeaways
- An
Enumis a fixed set of named constants; each member has anameand avalue. - Look up by value (
Color(2)) or name (Color["RED"]); iterate withfor c in Color. - Compare with
==oris; members are not equal to raw values and cannot be ordered (useIntEnumfor numbers). auto(),@uniqueandFlaghelp with values, aliases and combined options.- Members can have methods, properties and extra data; use them with
matchand store.valuein JSON.
Practice
1. Define an enum Suit with four members.
Show answer
class Suit(Enum):
HEARTS = 1
SPADES = 2
CLUBS = 3
DIAMONDS = 4
2. What is the difference between Color(1) and Color["RED"]?
Show answer
Color(1) looks up by value; Color["RED"] looks up by name. Both return Color.RED here.
3. Is Color.RED == 1 true?
Show answer
No, for a plain Enum it is False. For an IntEnum it would be true.
4. How do you combine read and write permissions in a Flag enum?
Show answer
With |: Perm.R | Perm.W. Test with Perm.R in combined.
5. What does @unique do?
Show answer
It raises ValueError if two members have the same value (an alias).
6. Why save status.value instead of status in JSON?
Show answer
json cannot encode a plain enum member, but it can encode the value (a string or number), which you convert back with Status(value).