pythonpytransitions

Pytransitions: Is it possible to change what model attribute the machine injects in the model?


I'm retrofitting the pytransitions state machine into an existing model, which happens to already have a column (the model also happens to be a SQLAlchemy model) that is named status.

I noticed that the transitions library injects a state field, but I'm not exactly sure if there's a way to change that field to my model's status column and have the transitions reflect on that particular field. If there's not a way currently, I'm thinking about using the machine.after_state_change callback and working from there.

Besides (ab)using that particular callback what would be a decent workaround?


Solution

  • As of 0.8.3 you can specify model_attribute on the Machine.

    >>> from transitions import Machine 
      2 class Matter(object): 
      3     pass 
      4  
      5 lump = Matter() 
      6 transitions = [ 
      7     { 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid' }, 
      8     { 'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas' }, 
      9     { 'trigger': 'sublimate', 'source': 'solid', 'dest': 'gas' }, 
     10     { 'trigger': 'ionize', 'source': 'gas', 'dest': 'plasma' } 
     11 ] 
     12 machine = Machine( 
     13     model=lump,  
     14     states=['solid', 'liquid', 'gas', 'plasma'],  
     15     initial='solid',  
     16     transitions=transitions,  
     17     model_attribute='my_state' 
     18 )
                                                           
    >>> lump.state                                     
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'Matter' object has no attribute 'state'
    
    'Matter' object has no attribute 'state'
    
    >>> lump.my_state                                  
    'solid'