Skip to the workspace
Pebellslearn by building
The Standard Toolbox  ›  Lesson

Enum

Enum 17 minAn enum defines a fixed set of named members for representing a limited set of meaningful states or choices.

An enum defines a fixed set of named members for representing a limited set of meaningful states or choices.

Convert external values at the boundary and use members consistently inside the program.

A misspelled status string can quietly skip the next step of a workflow. An enum gives the permitted states explicit names and identities. Learn how those members differ from their raw values, how external text becomes a member, and why a set of valid states still needs a separate rule for transitions.

A loose string "DONE" silently comparing False to a typo "DNOE" with no complaint, next to a traffic light housing three fixed named lamps RED/YELLOW/GREEN where Light.BLUE raises AttributeError because no fourth lamp exists

Order status without enum

A delivery app tracks each order's status as a string. It works — until one line checks the status against a misspelled string:

python

Nothing crashes. The archive step just silently never runs, and the bug could hide for months. An Enum turns the same typo into an error at the exact line that has it:

What happens when you run this?
from enum import Enum

class Status(Enum):
    PENDING = "pending"
    DONE = "done"
    FAILED = "failed"

print(Status.DNOE)

Two things worth knowing up front: an Enum member has both a .name and a .value, and it does not equal its raw value by default:

python

Preparing this topic’s interactive investigation…

Convert at the boundary, then use one representation

An API payload is text; internal decisions can use enum members. Convert once where the text enters, so the rest of the program does not repeatedly guess whether it received a string or a member.

python

Status("done") accepts the external value. Status["DONE"] looks up the member name; an unknown name raises KeyError instead. These two interfaces are intentionally different. Serialise .value when that is the external contract, and keep explicit values stable when other systems store them.

An enum limits the set of states but does not define legal transitions. DONE → PENDING still needs a rule. For a job workflow, draw allowed arrows and encode a transition mapping; reject an absent arrow instead of treating every enum member as reachable from every other member.

Transfer the traffic-light exercise to a job with PENDING, RUNNING, and DONE: specify which transition is allowed and which should fail. For numeric interoperability, use IntEnum deliberately: members can compare equal to ordinary integers, and arithmetic produces an integer rather than preserving membership. Ordinary Enum keeps that boundary stronger.

Traffic light states

A traffic light only ever has three states, and nobody wants to remember whether 1 means red or green. auto() hands out the numbers so you never have to pick them by hand:

python

For this ordinary Enum with default generation, auto() counts from 1 in definition order — reordering the lines changes the numbers, so never rely on the exact value if you used auto(), only on the name.

Priority levels that sort

A plain Enum gives you a fixed set, but not an order — two members can't be compared with < unless you ask for that specifically:

What happens when you run this?
from enum import Enum

class Priority(Enum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

print(Priority.LOW < Priority.HIGH)

IntEnum says so: a member is an int underneath, so ordering, sorting and even comparing to a plain number all just work:

python

Quick practice

What does this print?
from enum import Enum

class Suit(Enum):
    CLUBS = 1
    HEARTS = 2

print(Suit.CLUBS.value == 1, Suit(1) == Suit.CLUBS)
What does this print?
from enum import Enum

class Priority(Enum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

print([p.name for p in Priority])
broken — fix it

The function is supposed to work with either a string or a Status member. Right now only one of the two calls comes back True. Fix the comparison so both do.


🎯 Your turn

Write next_light(name). name is "RED", "GREEN" or "YELLOW" — the light's current state. Return the name of the next state in the cycle RED → GREEN → YELLOW → RED.

  • next_light("RED") → "GREEN"
  • next_light("YELLOW") → "RED"

Hint: define class Light(Enum): RED = 1; GREEN = 2; YELLOW = 3, keep ORDER = [Light.RED, Light.GREEN, Light.YELLOW], look up Light[name], find its index with .index(...), and step forward with % len(ORDER).

Press ▶ Run and hit ✓ Check. ✅

Your task
Write next_light(name): name is "RED", "GREEN" or "YELLOW", the light's current state. Return the name of the next state in the cycle RED -> GREEN -> YELLOW -> RED, using an Enum. Example: next_light("RED") -> "GREEN".

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upLook up a status's value

Define class Status(Enum): PENDING = "pending"; DONE = "done"; FAILED = "failed". Write status_value(name) returning the .value of the member whose name is name.

enum
DrillWhich priority wins

Define class Priority(IntEnum): LOW = 1; MEDIUM = 2; HIGH = 3. Write higher_priority(a_name, b_name) returning whichever name has the higher priority (on a tie, return a_name).

intenum
BuildRed suit or black suit

Define class Suit(Enum): CLUBS = auto(); DIAMONDS = auto(); HEARTS = auto(); SPADES = auto(). Write suit_color(name) returning "red" for DIAMONDS/HEARTS and "black" for CLUBS/SPADES.

enumauto
BossSort names by priority

Reuse Priority (LOW=1, MEDIUM=2, HIGH=3). Write sort_by_priority(names) returning names sorted from lowest to highest priority.

intenumsorted
CapstoneCycle the light forward n steps

Reuse Light (RED, GREEN, YELLOW in that cycle order). Write cycle_forward(name, steps) returning the name of the state reached after advancing steps times from name (steps can be 0 or larger than one full cycle).

enummodulo
Project context and further resources
next_light.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
next_light(name) → strThe name of the next state in the RED -> GREEN -> YELLOW -> RED cycle.
try:
returned
No app map for this section yet.
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.