Skip to content

Module 17 · Advanced Python Concepts — topic 14 of 14

Enums

Named constant sets with enum: Enum members, names and values, lookup by value and name, auto(), iteration, methods on enums, StrEnum and Flag, and using enums for state machines.

Beginner 10 min read·Lesson 260 of 306 in Python Programming

Learning objectives

  • Define and use Enum classes
  • Look up members by name and value
  • Use StrEnum, Flag and enum methods

Definition

An enumeration (enum) is a class whose members are a fixed set of named constants. enum.Enum members have a name and a value, compare by identity, and can be iterated, looked up and given methods.

Introduction

Order states, colours, user roles — when a value must be one of a few options, an enum is safer and clearer than loose strings like "shiped" (typo included).

Why it matters

Enums catch typos early, document the allowed values in one place and make code easier to read and refactor.

Detailed explanation

Define members as class attributes: class Color(Enum): RED = 1. Members are singletons: Color.RED is Color.RED.

Each member has .name ("RED") and .value (1). Color(1) looks up by value; Color["RED"] by name; invalid lookups raise ValueError or KeyError.

auto() assigns values automatically when the actual values don't matter.

Enums are iterable (for c in Color) and len(Color) counts members. Plain Enum members are not equal to their raw values (Status.PENDING == 1 is False).

Enums can have methods and properties, keeping behaviour next to the constants.

StrEnum and IntEnum members behave like strings or ints, convenient for JSON and databases. Flag supports combinations with | and membership tests with in.

Enums suit state machines: each state knows which transitions are allowed.

Syntax

Python
from enum import Enum, auto
class Status(Enum):
PENDING = auto()
SHIPPED = auto()
Status.SHIPPED.name, Status.SHIPPED.value
Status(1)
  • Members are named constants.
  • Look up by value or name.
  • auto() for automatic values.

Code examples

Members, names and values

Python
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED, Color.RED.name, Color.RED.value)
print(Color(2), Color["BLUE"], len(Color))
Output
Color.RED RED 1
Color.GREEN Color.BLUE 3

auto(), iteration and comparison

Python
from enum import Enum, auto
class Status(Enum):
PENDING = auto()
SHIPPED = auto()
DELIVERED = auto()
print([s.name for s in Status], Status.SHIPPED.value)
print(Status.PENDING == Status.PENDING, Status.PENDING == 1)
Output
['PENDING', 'SHIPPED', 'DELIVERED'] 2
True False

More examples

A state machine, StrEnum and Flag

Python
from enum import Enum, Flag, StrEnum, auto
class OrderState(Enum):
NEW = "new"
PAID = "paid"
SHIPPED = "shipped"
CANCELLED = "cancelled"
def can_move_to(self, other):
allowed = {
OrderState.NEW: {OrderState.PAID, OrderState.CANCELLED},
OrderState.PAID: {OrderState.SHIPPED, OrderState.CANCELLED},
}
return other in allowed.get(self, set())
state = OrderState.NEW
for target in [OrderState.SHIPPED, OrderState.PAID, OrderState.SHIPPED, OrderState.NEW]:
if state.can_move_to(target):
state = target
print("->", state.value)
else:
print(f"cannot go from {state.value} to {target.value}")
class Level(StrEnum):
LOW = auto()
HIGH = auto()
print(Level.HIGH == "high", f"level={Level.LOW}")
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
p = Perm.READ | Perm.WRITE
print(Perm.WRITE in p, Perm.EXECUTE in p, p)
Output
cannot go from new to shipped
-> paid
-> shipped
cannot go from shipped to new
True level=low
True False Perm.READ|WRITE

Step-by-step explanation

  • can_move_to keeps the transition rules inside the enum, so invalid moves are rejected in one place.
  • StrEnum members equal their lower-case string values, which is handy for JSON and databases.
  • Flag members combine with | and are tested with in.

Expected output

Running “A state machine, StrEnum and Flag” prints exactly:

TextOutput
cannot go from new to shipped
-> paid
-> shipped
cannot go from shipped to new
True level=low
True False Perm.READ|WRITE

Practical applications

  • Order and payment statuses in e-commerce.
  • File permissions and feature flags.

Best practices

  • Use enums for fixed sets of options.
  • Compare members, not raw values.
  • Use StrEnum when values are stored as text.

Common mistakes

Comparing members with raw values

Avoid

if status == "shipped": # always False for Enum

Prefer

if status is OrderState.SHIPPED:

Plain Enum members don't equal their values; compare members.

Important notes

  • match statements work well with enums: case OrderState.PAID: ...

Key takeaways

  • Enums define named constants with name and value.
  • Look up with Enum(value) and Enum[name].
  • StrEnum, IntEnum and Flag cover special needs.

Try it yourself

  1. 1
    Create a TrafficLight enum with a next() method cycling RED → GREEN → YELLOW → RED.
  2. 2
    Model user roles with Flag and check whether a user can edit.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic