Sub topic 1
Defining your first Enum
Prerequisites
This chapter assumes you can:
- Write a Python class and read class attributes.
- Write functions and methods, and recognize a decorator.
- Explain the difference between
==(equal value) andis(same object). - Loop over a collection with
for.
You need Python 3.8 or newer. Later chapters mention Python 3.11+ features, and those are marked when they appear.
Why an enum instead of constants
A program often has a small, fixed set of choices: order states, log levels, compass directions. A common first approach is to use plain strings or integers:
def ship(order_status):
if order_status == "shipped":
return "already on its way"
return "preparing"
print(ship("shiped")) # preparing (typo, no error)The typo "shiped" is a valid string, so Python accepts it and the function quietly takes the wrong branch. Nothing connects the string in the caller to the string in the function.
An enumeration (enum) is a named set of constants, defined once and used by name everywhere. Python's standard enum module provides the Enum base class. A misspelled member name fails immediately with an AttributeError, and members print readably. They also cannot be silently changed or confused with unrelated values.
The basic syntax
You define an enum by subclassing Enum and assigning values to names in the class body:
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) # 1
print(type(Color.RED)) # <enum 'Color'>Each assignment in the body creates one member. A member is an object that has a name (the identifier you wrote) and a value (the right-hand side). Color.RED is not the integer 1. It is an instance of Color that carries the value 1.
The two printed forms differ on purpose:
| Call | Result for `Color.RED` | Purpose |
|---|---|---|
| `str(Color.RED)` or `print(...)` | `Color.RED` | Readable form for users and logs |
| `repr(Color.RED)` | `<Color.RED: 1>` | Debugging form that includes the value |
Naming conventions
The Python documentation and most codebases follow these conventions:
- Name the class in
PascalCase, in the singular:Color, notColors. A variable of this type holds one color. - Name members in
UPPER_CASE, as you would for constants. - Do not use a leading or trailing single underscore on member names (such as
_RED_). Names of the form_sunder_are reserved for the enum machinery.
What kind of object is a member
Several facts follow from the way the class is built.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
print(isinstance(Color.RED, Color)) # True
print(Color.RED is Color(1)) # True
print(len(Color)) # 2
print(list(Color)) # [<Color.RED: 1>, <Color.GREEN: 2>]
print(bool(Color.RED)) # True- Each member is an instance of its enum class.
isinstance(Color.RED, Color)isTrue. - Each member is a singleton. Only one
Color.REDobject exists. That is whyiscomparisons work, and it is the main reason to preferiswhen you compare members (the comparison rules get their own chapter). - The class is iterable and has a length. Iteration follows definition order. The class's own type is a metaclass,
EnumType(namedEnumMetabefore Python 3.11), which supplies this behavior. - Members are truthy by default. Even a member whose value is
0evaluates asTrue, unless you mix in a type such asintthat defines its own truth rules. If you need falsy members, define__bool__yourself.
The class body also differs from an ordinary class in one important way. Python does not store RED = 1 as the integer 1 on the class. The EnumType machinery intercepts each assignment and replaces it with a member object. A diagram of the process:
Values can be any type
Values do not have to be integers, and they do not have to share a type:
from enum import Enum
class Mixed(Enum):
NUMBER = 1
TEXT = "two"
PAIR = (3, 4)
print(Mixed.TEXT.value) # two
print(Mixed.PAIR.value) # (3, 4)Strings are the most common choice when the value is stored in a file, a database, or a JSON message. Integers are common for ordering or interoperating with C libraries. Choose values that are stable. Once other systems store your values, changing them breaks those systems, while renaming a member does not.
What counts as a member
Not every name in the class body becomes a member. The rule is roughly this: plain data assignments become members, and anything that behaves as a descriptor does not. Functions, property objects, classmethod objects and staticmethod objects are all descriptors, so they stay ordinary attributes of the class.
from enum import Enum
class Weekday(Enum):
MONDAY = 1
TUESDAY = 2
def is_first(self):
return self is Weekday.MONDAY
print(list(Weekday)) # [<Weekday.MONDAY: 1>, <Weekday.TUESDAY: 2>]
print(Weekday.MONDAY.is_first()) # True
print(Weekday.TUESDAY.is_first())# Falseis_first is a method, so it does not appear in list(Weekday) and does not count toward len(Weekday). A later chapter covers methods, properties and extra fields in depth. For now, remember that a name is a member only if its value is not a descriptor and its name is not a reserved form.
Names with double underscores at both ends (__doc__, __module__) are also never members. Because of this, you can write a docstring in an enum class body without creating a member:
from enum import Enum
class Suit(Enum):
"""The four suits of a standard deck."""
HEARTS = "H"
SPADES = "S"
print(Suit.__doc__) # The four suits of a standard deck.
print(len(Suit)) # 2Rules the class enforces
An enum protects its set of members. These protections are what separate an enum from a class full of constants.
Members cannot be reassigned
from enum import Enum
class Color(Enum):
RED = 1
try:
Color.RED = 5
except AttributeError as error:
print("AttributeError:", error)Assigning to an existing member name raises AttributeError. The exact message differs between Python versions, so do not depend on its text. Deleting a member raises AttributeError as well.
You cannot create new members by calling the class
Calling the class, as in Color(1), does not construct a new object. It looks up the existing member with that value:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
print(Color(1)) # Color.RED
try:
Color(99)
except ValueError as error:
print("ValueError:", error) # 99 is not a valid ColorA value that matches no member raises ValueError. The next chapter covers lookups by value and by name in full.
Names cannot be repeated
If you write the same name twice in a class body, Python raises TypeError while building the class. A normal class would just let the second assignment win. The enum rejects it because the two assignments would mean two different members with one name.
from enum import Enum
try:
class Broken(Enum):
RED = 1
RED = 2
except TypeError as error:
print("TypeError:", error)This is different from two names sharing one value, which is legal and creates an alias. The chapter on iteration and aliases explains that case.
Enums with members cannot be subclassed
You cannot extend an enum that already has members:
from enum import Enum
class Color(Enum):
RED = 1
try:
class MoreColor(Color):
BLUE = 2
except TypeError as error:
print("TypeError:", error)The set of members is fixed once the class is created. That guarantee is what lets you write code that handles every member. An enum with no members can be subclassed, which is useful for sharing methods between several related enums:
from enum import Enum
class LabeledEnum(Enum):
def label(self):
return self.name.replace("_", " ").title()
class Size(LabeledEnum):
VERY_SMALL = 1
LARGE = 2
print(Size.VERY_SMALL.label()) # Very SmallCommon mistakes when defining enums
- Expecting the member to equal its value.
Color.RED == 1isFalsefor a plainEnum. Compare toColor.RED, or use.valuewhen you need the raw value. Section onIntEnumlater in this tutorial shows the alternative. - Writing members as instances. Writing
Color.RED = Color(1)orRED = Color.REDinside the body is not how members are declared. Assign the raw value only. - Using a list or dict as the only way to enumerate choices. If you need a fixed set of named options, an enum gives you iteration, membership checks, and error messages that a list of strings does not.
- Defining a function as a "constant". If you assign a function or lambda to a name in the body, it becomes a method, not a member. This surprises people who try to store callables as values. Wrap the function in a tuple or use
functools.partialif you need the callable as a value. - Forgetting that the class name is part of the output.
str(Color.RED)isColor.RED, notRED. If you need only the name for display or serialization, use.nameexplicitly.
Putting it together
Here is the typo example from the start, rewritten with an enum:
from enum import Enum
class OrderStatus(Enum):
PENDING = "pending"
SHIPPED = "shipped"
DELIVERED = "delivered"
def ship(status: OrderStatus) -> str:
if status is OrderStatus.SHIPPED:
return "already on its way"
return "preparing"
print(ship(OrderStatus.SHIPPED)) # already on its way
print(ship(OrderStatus.PENDING)) # preparing
try:
ship(OrderStatus.SHIPED) # misspelled member
except AttributeError as error:
print("AttributeError caught")The misspelling now fails at the moment the line runs, with an AttributeError, instead of silently selecting the wrong branch. A static type checker such as mypy would flag it before the program even runs.
Exercise
What does this code print, and why? from enum import Enum class Light(Enum): RED = 0 GREEN = 1 def describe(self): return self.name.lower() print(len(Light)) print(bool(Light.RED)) print(Light.GREEN.describe()) print(Light.RED == 0)
Show answer
It prints 2, True, green and False. len(Light) is 2 because describe is a function, so it is a method and not a member, leaving only RED and GREEN. bool(Light.RED) is True because members of a plain Enum are truthy by default, even when the value is 0. describe() returns the lowercase name, "green". Light.RED == 0 is False because a plain Enum member is a distinct object that does not compare equal to its raw value.
Exercise
You write class Shade(Color): DARK = 4 where Color is an Enum that already defines RED, GREEN and BLUE. What happens, and what is a legitimate way to share behavior between enums?
Show answer
Python raises TypeError when the class statement runs, because an enum that already has members cannot be subclassed. To share behavior, define a base enum that has methods but no members, and subclass that base in each enum that needs the methods.