State Pattern in Python
State replaces large conditionals with state objects that implement state-specific behavior.
What is State Pattern?
State replaces large conditionals with state objects that implement state-specific behavior.
Change an object's behavior when its internal state changes.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example code
main.py
class Playing:
# State: delegate behavior to the current state object.
def action(self): return "Playing"
class Paused:
def action(self): return "Paused"
class Player:
def __init__(self): self.state = Paused()
def set_state(self, state): self.state = state
def action(self):
# Behavior comes from the current state object.
return self.state.action()
player = Player()
player.set_state(Playing())
print(player.action())
player.set_state(Paused())
print(player.action())
Expected output
Playing
Paused
How it works
Player delegates its action to the current state and can switch states at runtime.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.