Sitemap

Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Designing a State Machine in Python for 2025: A Clear Introduction

3 min readMay 21, 2025

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.

Press enter or click to view image in full size
Talking about Python FSMs on vacation — because code never really takes a break

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_by and is_overdue().
    All we really need is “book is overdue”, yet it’s buried in logic.

The same check after making state explicit

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web
Already have an account? Sign in
Dev Genius

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Aleksei Aleinikov

Written by Aleksei Aleinikov

Insights in AI, Python, JavaScript, TypeScript, Go, React & Next.js. Sharing IT news, Data and DevOps tips & Cloud Solutions. Follow for deep dives into Tech!

No responses yet

Write a response