State Pattern Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓State Pattern runs in O(1) time and O(n) space, in Python as in every other language.
- ✓enum.Enum names the states and enum.auto assigns values. The match statement, added in 3.10, destructures both the state and any payload, and a dictionary keyed by the current state mapping to a handler is the table-driven form that avoids a long if-chain.
- ✓Use an Enum rather than string constants so a typo is an AttributeError at the point of use instead of a silently unmatched branch.
- ✓The Python trap: Python cannot check exhaustiveness, so a match over states with no catch-all silently falls through and returns None when a new state is added, which is the failure this pattern exists to prevent.
- ✓Enum member access goes through a metaclass lookup and is noticeably slower than comparing plain integers or strings, which matters only in very hot loops; caching the member in a local removes it.
What State Pattern actually is
State Pattern in Python: what you actually reach for
Python implementation
from enum import Enum, auto
from typing import NoReturn, assert_never
class State(Enum):
DRAFT = auto()
REVIEW = auto()
PUBLISHED = auto()
ALLOWED: dict[State, frozenset[State]] = {
State.DRAFT: frozenset({State.REVIEW}),
State.REVIEW: frozenset({State.DRAFT, State.PUBLISHED}),
State.PUBLISHED: frozenset(),
}
class Post:
def __init__(self) -> None: self.state = State.DRAFT
def to(self, nxt: State) -> None:
if nxt not in ALLOWED[self.state]:
raise ValueError(f"illegal: {self.state.name} -> {nxt.name}")
self.state = nxt
def label(s: State) -> str:
match s:
case State.DRAFT: return "Draft"
case State.REVIEW: return "In review"
case State.PUBLISHED: return "Live"
case _:
# assert_never (3.11+) makes a type checker REPORT a missing case.
assert_never(s)Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for State Pattern?
enum.Enum names the states and enum.auto assigns values. The match statement, added in 3.10, destructures both the state and any payload, and a dictionary keyed by the current state mapping to a handler is the table-driven form that avoids a long if-chain. enum.StrEnum, from 3.11, is convenient when states are persisted. For the class-per-state form, abc.ABC defines the interface each state must implement.
What is the most common Python mistake when implementing State Pattern?
Python cannot check exhaustiveness, so a match over states with no catch-all silently falls through and returns None when a new state is added, which is the failure this pattern exists to prevent. Always write a case underscore branch that raises. Type checkers can help: assigning the matched value to a variable annotated NoReturn in the final branch makes mypy report a missing case, which is the closest Python gets to the compile-time proof the static languages have, and it is worth the two extra lines.
How does State Pattern actually perform in Python?
Enum member access goes through a metaclass lookup and is noticeably slower than comparing plain integers or strings, which matters only in very hot loops; caching the member in a local removes it. A dictionary dispatch is one hash lookup and beats a long if-elif chain once there are more than a handful of states, since the chain is linear. The class-per-state form adds an attribute lookup and a method call per transition, which is the usual Python call cost. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.