Skip to contentSaltar al contenido
125+ QA and SEO checks per page

State Pattern Implementation in Python

14 min readintermediate
Website QA and SEO audits

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

The State pattern lets an object change its behaviour when its internal state changes, by delegating to a per-state object rather than branching on a flag. Written out as classes it is unremarkable; what makes it worth eight separate pages is that this is the pattern where type systems differ most sharply. The real question is not how to represent a state but whether the compiler will tell you when you forget to handle one, and whether it can stop an illegal transition from being written at all. Three languages here prove exhaustiveness at compile time and turn a forgotten state into a build failure. One goes further and can make an invalid transition fail to compile by encoding the state in the type itself. One has an enum construct built specifically for this pattern. And two cannot check any of it, so the discipline has to live in tests.

State Pattern in Python: what you actually reach for

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.

Python implementation

Use an Enum rather than string constants so a typo is an AttributeError at the point of use instead of a silently unmatched branch. Drive transitions from a dictionary of state to allowed next states, so the legality of a transition is data you can test and print rather than logic spread across methods. Keep the state objects stateless and share one instance per state, since they hold behaviour and not data.
python
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 Free

The Python-specific 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. 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.

Performance in Python, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port State Pattern between languages.

Real-World Applications

State Pattern is used extensively in production software: framework internals, plugin architectures, state management libraries, and large-scale application architectures all rely on this pattern. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding State Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

State Pattern appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose State Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of State Pattern to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Most AI and dev tools have a student plan. See which ones and how to claim them on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.