Ventures of an ex indie game developer

Alarm... or at least invisible statefulness

I eventually started working on my alarm. Or er... It's like this: every time I write a Python program I can't just write it. I need to poke around with the code, and hopefully learn something sweet. But usually just poke around.

This time I realized I wanted a state machine (not that I needed one). No, not a big and bloated one! I wanted
  1. a tiny one
  2. which I could write state machine components (as opposed to frameworks) in,
  3. but I didn't want to declare states and transitions, just write code.
My component should preferably be written something like this:
while not alarm_active(): wait(a_little_bit)
while alarm_active() and not alarm_sensor_indicating_something(): wait(some_more)
if alarm_active() and alarm_sensor_indicating_something():
    start_screaming(like_a_girl)
    wait(a_minute)
    stop_screaming()
But if it's going to be a component (not an application nor a bloody framework), it can't be fire and forget. I wanted to call it with something like:
my_alarm_state_machine.tick()
Then I thought of the yield statement, and realized I could use that to keep the stack as long as I write my state machine in a single function. No state machine should ever be longer than a single function anyway. (If you need to, you could always create sub-state machines in the methods you're calling.) Besides, you automatically get all the error handling you need in the same place. Peuh, this is starting to look good!

When I'd written it I realized I was proud over some code I'd written for the first time in many, many years. Here is part of an example I made:

Three lines of code to start and tick the state machine, no extra lines in the actual code itself. It doesn't even look like a state machine, it just looks like tickable code. Great Scott! Best part of all? The state machine source is 19 lines of code. Python still rocks my world from time to other.

Fetch the source and a couple of examples from github:
git clone https://github.com/highfestiva/generatorstate.git

About the author

Mitt foto
Gothenburg, Sweden