The State Design Pattern in Python Explained

preview_player
Показать описание

In this video, I'll dive into the State Design Pattern in Python, a game-changer for managing state changes in object-oriented programming.

🔖 Chapters:
0:00 Intro
1:09 What is the State Design Pattern?
1:25 Basic Example
3:54 Example 2: Document editing
8:55 Example 3: Game states
17:24 When to use the State pattern?
18:34 Final thoughts

#arjancodes #softwaredesign #python
Рекомендации по теме
Комментарии
Автор

I think you forgot to mention that states are really useful for physical machine safety. Robots for example. It avoids having if-red-button-pressed kind of code all over the place, which will guaranteed be forgotten in one place. With proper state design, the red button press will only put the machine in SafetyState, which happens to be a single source file, conveniently listing all possible actions and state transitions, thereby greatly reducing the risk of oversight.

ErikBongers
Автор

Totally relevant design pattern.
I use one in my python based virtual assistant to speed up and make robust my microphone input code.
States: listening, understanding, responding

MrGeordiejon
Автор

I'm finally to a point, where I can appreciate your videos! I watched this, about 6 months ago, when I first heard of state machines... and it was mostly lost on me. so I had to put in some work, and now, we're here. This is all, just to say, thank you. Thanks for the help, thanks for the motivation, and thanks for the free education! cheers!

ronboprime
Автор

For the first time in last 2 years, I have no idea what the code did, just by looking at it, until a google search. Damn, you surely make advanced videos on Python and the more I dive into it, the more I get to learn, every single time 😅

VivekKumarSinha
Автор

You're such a great teacher. I really like the way you build a concept from simple examples and explain how they might useful in real cases. Congratulations

gabrielcanuto
Автор

1987, my first project, TurboPascal, MSDOS, 640 kB ram.
It was about translating textual descriptions into graphics for hercules, ega, and printer.
I created some integer drawing algorithms and an interpreter for the description language.
This part went quite well, i was a bit proud.
There was also some user interface part, which made me crazy,
because i tried to implement the state changes implicitly, on the fly,
by intruducing some variables without any specific concept in my mind.
The problem looked so easy, but it didnt work, the logic was distributed and incomplete.
I felt quite stupid, that i couldnt get a grip on it.
Then i suddenly recognized, that a state machine will solve my problem.
It was so easy now.
Years later i used statemachines heavily in a WinNT/c++ computer telephony application, to handle the user interface for things like 'Dear Friend, if you want to talk to <bla> press 5, else if you ...' etc.
We described the states, statechanges, wav-files, options and actions in a config.
Technically it was a nice project, multithreaded parallel statemachines that could interact.

It's quite cool to be software developer ;-)

torwine
Автор

Dear Arjan, thank you for your amazing videos, and once again, a perfect match between didactic and humor material. With respect to the design pattern presented in this video, I would like to discuss in more depth the implications of its use. Especifically, I noticed that this pattern impose a certain degree of redundancy and coding rewriting, since all inherented classes from the abstract (or the Protocol) class must implement its own definitions of each abstract method. This problem became very clear in your Draft/Document coding example. At that example, each class had to implement all methods that the base (abstract) class declared, even in cases in which the derived state class (e.g., Finalized class) does not have any real functionality (method); this Finalized class does basically nothing, since the document is already finalized. From a strongly typed language point of view (e.g., C#, or C++), I see several problems with this pattern; as it stands, there would be a constant need of casting operations in order to overcome that redundancy coding that was mentioned at the beginning of this paragraph. Let me know your comments in this regard. Sincerely,

philiperiskallaleal
Автор

I really needed this explanation! I've reached the point in my game development where there are too many if statements to check what state I'm in and perform different actions within each of the public methods. Instead, I can put each of these different behaviors in its own state, and have the context keep track of online players/admins etc.

Braekpont
Автор

For anyone new to state machines, I'd also recommend pytransitions as a library! Cheers!

SidathWijesooriya
Автор

I have used the state design pattern and also for video games development :) . But like it usually happens I used a variation. I used it for changing a boss' behavior depending on his current phase, so I added a method for checking whether a phase change should happen, and I also added an on_enter method to make the boss make an 'opening' sort of move, signaling the change of phase for the player. I loved it because it makes sense both from the player perspective as well as from the programmer perspective.

lucianop.
Автор

Been watching since you started your channel! Your design pattern videos are the best. Thank you.

manonthedollar
Автор

Love it, never knew about this state pattern, thank you for educating the public!

tomvonheill
Автор

Hi Arjen, great video,

In the bulb example you do not need the LightState Protocol class at all, it's not being used. I thought for a second that there was some magic going on.

Carloes
Автор

I strongly belive part II will cover right ways to decoupling states, adding new state without refactoring previous states, controlling possible transitions in one place.

MrTrebor
Автор

Seems like you are rewarded by the lines of code :-) For that, such solutions are excellent!

jan.kowalski
Автор

In the context of automation you will use state patterns to describe a process or a simple machine. And you can use some frameworks. For example in python you can use library like 'transitions' or 'automate'.

THElalouloute
Автор

glad to see a design pattern video again! the state pattern is fun to me specifically because years ago I helped my sister make a game for a python class she had to take. While I didn't know about patterns at the time, I knew enough about how to avoid ending up with spaghetti code and getting overwhelmed that we ended up "inventing" the state pattern organically as we built the game. When I learned about patterns later, having stumbled into one on my own previously helped me intuitively grasp the idea.

xiggywiggs
Автор

I found a good place to use the state pattern is in a parser I was writing. The goal is to parser through an xml file and by using states I was able to handle it as a file stream rather than loading the entire file and creating a nested dictionary in memory.

mrrobotman
Автор

A game programming book was my first encounter with finite state machines in programming as well.

quillaja
Автор

The only thing outside game engines I have ever worked on a state machine was a custom app our company made to auto discover scan/audit customer computer networks and devices configs. The main thread used states to control the phases of work it had to do discovering and dispatching worker threads until there was no more targets to gather and sanitize info into a sqlite db as a temp cache. It then would export the temp db to CSV files used to generate a website from templates and upload it to an internal web server for users to browse the data and download the CSVs if they needed. It was educational porting it from Py 2.7 to 3.3 a few years ago.

eltreum