Replacing Conditionals with the State Pattern in Python
This article explains how the State pattern replaces chains of conditions with one class per state, when a transition table over an Enum is clearer, and which errors appear when state data is misplaced.
An object whose behaviour depends on its current situation, such as a media player that may be stopped, playing or paused, is often written with a variable that records the situation and a chain of conditions in every method that consults it. The present article examines the State pattern, which replaces those chains with one class per state and lets the object delegate each operation to the class that represents its current state. It shows the conditional version that the pattern replaces, implements the pattern with state objects that are shared because they hold no data, compares it with a table of transitions built on Enum, and describes the errors that appear when transitions or data are placed in the wrong object. Writing the rules of each state in one place, and letting the object change its behaviour by replacing a single reference, is the secret weapon of the State pattern.
The Conditional Version and Its Growth
A media player with three states and two buttons is enough to show the difficulty. Each method must ask in which state the player is, and every new state or button adds a branch to every method.
class MediaPlayer:
def __init__(self):
self.state = "stopped"
def press_play(self):
if self.state == "stopped":
self.state = "playing"
return "start from the beginning"
elif self.state == "playing":
self.state = "paused"
return "pause"
elif self.state == "paused":
self.state = "playing"
return "resume"
def press_stop(self):
if self.state == "stopped":
return "already stopped"
self.state = "stopped"
return "stop"
player = MediaPlayer()
print(player.press_play(), "|", player.press_play(), "|", player.press_stop())
# Output: start from the beginning | pause | stop
The rules of the state "paused" are scattered across both methods, and a misspelled string, such as "pased", would silently fall through every branch. With a few states and buttons the code remains readable, but the number of branches grows with the product of states and operations.
One Class per State
Role-playing games often let a character take different forms, so that the same key triggers a different ability in each form and the character itself only remembers which form it currently has. The State pattern organizes an object in the same way: the context, here the player, keeps a reference to a state object and forwards every operation to it, and each state class implements all the operations for its own situation and decides which state comes next. The analogy, however, stops at this point, because in a game the player chooses the form, whereas in the pattern the transition is normally decided by the state objects themselves.
class Stopped:
def play(self, player):
player.state = PLAYING
return "start from the beginning"
def stop(self, player):
return "already stopped"
class Playing:
def play(self, player):
player.state = PAUSED
return "pause"
def stop(self, player):
player.state = STOPPED
return "stop"
class Paused:
def play(self, player):
player.state = PLAYING
return "resume"
def stop(self, player):
player.state = STOPPED
return "stop"
STOPPED, PLAYING, PAUSED = Stopped(), Playing(), Paused()
class MediaPlayer:
def __init__(self):
self.state = STOPPED
def press_play(self):
return self.state.play(self)
def press_stop(self):
return self.state.stop(self)
player = MediaPlayer()
print(player.press_play(), "|", player.press_play(), "|", player.press_play())
# Output: start from the beginning | pause | resume
print(type(player.state).__name__, player.state is PLAYING) # Output: Playing True
The class MediaPlayer no longer contains any condition, and all the rules of the paused state are in Paused. Since the state objects hold no data of their own, a single instance of each serves every player, which avoids creating a new object on every transition, the sharing technique examined in the article devoted to the Flyweight pattern. The structure resembles the Strategy pattern, since in both cases an object delegates to an interchangeable collaborator; the difference is that a strategy is chosen by the client, whereas a state is replaced by the states themselves as a consequence of the operations.
A Table of Transitions
When states differ only in where each event leads and in a short action, a table describes the machine more compactly than a class per state. An Enum names the states, so that a misspelling raises an error, and a dictionary maps each pair of state and event to the next state and the action.
from enum import Enum
class State(Enum):
STOPPED = "stopped"
PLAYING = "playing"
PAUSED = "paused"
TRANSITIONS = {
(State.STOPPED, "play"): (State.PLAYING, "start from the beginning"),
(State.PLAYING, "play"): (State.PAUSED, "pause"),
(State.PAUSED, "play"): (State.PLAYING, "resume"),
(State.PLAYING, "stop"): (State.STOPPED, "stop"),
(State.PAUSED, "stop"): (State.STOPPED, "stop"),
}
def handle(state, event):
try:
return TRANSITIONS[(state, event)]
except KeyError:
raise ValueError(f"event {event!r} is not allowed in state {state.value!r}") from None
state = State.STOPPED
for event in ("play", "play", "stop"):
state, action = handle(state, event)
print(action, "->", state.value)
# Output: start from the beginning -> playing
# Output: pause -> paused
# Output: stop -> stopped
try:
handle(State.STOPPED, "stop")
except ValueError as error:
print(error) # Output: event 'stop' is not allowed in state 'stopped'
Every allowed transition is visible in one place, and an event that the table does not list is rejected explicitly instead of being ignored. The value of the enumeration also gives a stable name for storing the state in a file or a database, whereas a state object would have to be translated before being saved. For a few states, a match statement on the pair (state, event) offers a third form, described in the article devoted to structural pattern matching.
Pitfalls of the State Pattern
The pattern distributes the rules of an object across several classes, so its errors usually come from putting a rule or a piece of data in the wrong one. Six pitfalls are distinguished, which are the following:
- Per-object data in shared states. A state instance shared by many contexts must not store data that belongs to one of them; that data belongs in the context.
- Transitions spread everywhere. Since each state decides the next one, adding a state requires changing every state that leads to it, and the complete machine is visible only by reading all the classes.
- Silent invalid events. An operation that is not meaningful in a state should raise an error or be documented as ignored, rather than doing nothing by accident.
- States that reach into the context. A state that manipulates many attributes of the context couples the two classes tightly; the context should expose a small set of operations.
- Too many classes. A machine with many states and trivial actions is clearer as a table than as a class per state.
- Persistence. State objects cannot be stored directly; a stable name, such as the value of an enumeration, is needed to save and restore the state.
The first pitfall is reproduced in the following example.
class Playing:
def __init__(self):
self.position = 0 # per-player data in a shared state: an error
def tick(self, player):
self.position += 1
SHARED_PLAYING = Playing()
class Player:
def __init__(self):
self.state = SHARED_PLAYING
first, second = Player(), Player()
first.state.tick(first)
first.state.tick(first)
print(second.state.position) # Output: 2
The second player reports a position of two although it never played, because both players share the same state object and the position was stored there. The position belongs to each player, so the state should update player.position, and the state object should remain free of data that varies between contexts.
Choosing a Representation for States
Consequently, the representation depends on how much behaviour each state carries and on how often the machine changes, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Two states and one or two conditions | A boolean or a simple if |
| Few states, each with substantial behaviour | The State pattern, one class per state |
| Many states with short actions | A transition table with Enum |
| Transitions that must be inspected or stored | A table and the enumeration values |
| The client chooses the behaviour, not the object | The Strategy pattern |
| A few pairs of state and event | match on (state, event) |
Conclusion
It is concluded that the State pattern replaces repeated conditions on a state variable with one class per state, to which the context delegates its operations and which decides the next state, and that in Python stateless state objects can be shared, while a table of transitions over an enumeration is often the clearer choice for machines with many states and simple actions. This magic depends on keeping per-object data in the context and on making invalid events explicit, since otherwise a shared state object or a missing transition hides the error. Registering every subclass of a base class automatically, for example every state of a machine, is possible with the hook __init_subclass__, which is developed in a future article of this series.