What is the Pythonic way to implement a simple FSM?

后端 未结 7 1625
猫巷女王i
猫巷女王i 2021-01-31 21:50

Yesterday I had to parse a very simple binary data file - the rule is, look for two bytes in a row that are both 0xAA, then the next byte will be a length byte, then skip 9 byte

7条回答
  •  执笔经年
    2021-01-31 22:41

    I am a little apprehensive about telling anyone what's Pythonic, but here goes. First, keep in mind that in python functions are just objects. Transitions can be defined with a dictionary that has the (input, current_state) as the key and the tuple (next_state, action) as the value. Action is just a function that does whatever is necessary to transition from the current state to the next state.

    There's a nice looking example of doing this at http://code.activestate.com/recipes/146262-finite-state-machine-fsm. I haven't used it, but from a quick read it seems like it covers everything.

    A similar question was asked/answered here a couple of months ago: Python state-machine design. You might find looking at those responses useful as well.

提交回复
热议问题