State Pattern in Python

Learn to implement state pattern and finite state machines using Python.
Read more…

:writing_hand:t3: Brought to you by one of our Guest Authors crew: Giridhar Talla

1 Like

What’s up Devs! How did you like this post? Please share any comments or feedback with us on this thread :speaking_head:

Nice article and beautiful example :slight_smile:

1 Like

Thanks! Glad you liked it!

perfect explanation of the pattern

The post was really helpful, thanks for the work!

There’s only one thing I didn’t understand, and it was the abc import and the abstractmethod decorator, but I’m trying to read up on them right now.

Sure! Let us know if you have any questions down the road!

This was a really nice post!

I think when talking about design patterns it is always to step back and see how to get the most out of the built-in language features. I’ve seen many times that design patterns written in Python look rather similar to Java code than traditional Python. This is not the case and I think it is amazing! I think it could be a good idea to use of Protocols instead of ABC for the State Class and maybe use dataclasses as well.

1 Like

Thanks for the input @ELC !

Instead of storing the Context as a variable in the States, requiring an extra step in set_state() (and making the state unnecessarily mutable), you can simply pass Context into the States’ doSomething() calls. Or, if there’s nothing to glean from Context, you can skip passing it in by having the States’ doSomething() methods return the new state instead instead of setting it on the Context.

i.e.

class Context:
def init(self, starting_state):
self._state = starting_state

def doSomething(self):
    self._state = self._state.doSomething()

class StateOne:
def doSomething(self):
return StateTwo()

class StateTwo:
def doSomething(self):
return StateOne()

And, if the State types are truly stateless and immutable, you can make cached versions of them.