Member-only story
Designing a State Machine in Python for 2025: A Clear Introduction
Every software object lives through phases. A library book can be “On Shelf”, “Reserved”, “Borrowed”, “Overdue”; a pizza order goes “Created”, “Cooking”, “Delivering”, “Delivered”.
Making those phases explicit wipes out cryptic conditionals and boosts readability.
State machines without scary math
- Finite set of states — their number is limited.
- Exactly one active state at any given moment.
- Strict transition rules define legal moves.
Fun fact: regex engines use state machines internally, which explains their speed.
A “bad” snippet with implicit state
if (book.borrower and
(datetime.now() - book.borrow_date).days > 30) or \
(book.reserved_by and book.is_overdue()):
notify_librarian(book)What happens here
- We check
borrower. - Compute days since
borrow_date. - Plus an extra branch with
reserved_byandis_overdue().
All we really need is “book is overdue”, yet it’s buried in logic.