Python FSM Fysom Callbacks Differently

I use Fysom to create FSM. I want to use callbacks in another way:

TABLE = {
'initial': 'OFF',
'events': [{'name': 'load', 'src': 'OFF', 'dst': 'LOADED'},],
'callbacks': {'onload': myfunction,}}

fsm = Fysom(TABLE)

Here, if I run fsm.onload(), it will execute myfunction. Instead, I want, if I run myfunction(), it dines fsm.onload().

I looked at the script and related part:

def _enter_state(self, e):
    '''
        Executes the callback for onenter_state_ or on_state_.
    '''
    for fnname in ['onenter' + e.dst, 'on' + e.dst]:
        if hasattr(self, fnname):
            return getattr(self, fnname)(e)

I do not see how to change this world of code for my purpose.

+4
source share
1 answer

You cannot implement callbacks "in the other direction" without touching myfunction. A callback is actually an inverted call ( Hollywood principle ), so a callback callback is a simple call.

, myfunction . , myfunction.

:

  • myfunction :

    def outer():
        fsm = Fysom(TABLE)
        def myfunction():
            print("I call the state machine transition when called")
            fsm.onload()
        return fsm
    
  • :

    class Foo(object):
    
        def __init__(self):
            self.fsm = Fysom(TABLE)
    
        def my_method(self):
            self.fsm.onload()
    
  • decorator, / .

    fsm = Fysom(TABLE)
    
    @transition(fsm, "onload")
    def myfunction():
        pass
    

    , fsm.

+4

Source: https://habr.com/ru/post/1536953/


All Articles