pytransitions / transitions

A lightweight, object-oriented finite state machine implementation in Python with many extensions
MIT License
5.52k stars 525 forks source link

Dynamically add/remove tags to state #384

Closed lakenn closed 4 years ago

lakenn commented 4 years ago

Think it would be very helpful if the tags can be added/removed dynamically.

Eg. this can act as the outstanding tasks to be completed when a state is entered.

aleneum commented 4 years ago

Hi @lakenn,

Think it would be very helpful if the tags can be added/removed dynamically.

They can. Tags are saved as a list of strings attached to the State object. Adding and removing tags should not be an issue:

from transitions import Machine
from transitions.extensions.states import add_state_features, Tags

@add_state_features(Tags)
class TagMachine(Machine):

    @property
    def current_state(self):
        return self.get_state(self.state)

    def convert(self):
        """converts state C from an error state to a success state"""
        state_c = self.get_state('C')
        state_c.tags.remove('error')
        state_c.tags.append('success')
        print(state_c.tags)

states = ['A', {'name': 'B', 'tags': ['pending']}, {'name': 'C', 'tags': ['error']}]
m = TagMachine(states=states, initial='A')
#  currently, C is an error state since 'convert' has not been called
m.add_transition('process', 'B', 'C', before='convert')
m.to_C()
assert m.current_state.is_error
m.to_B()
m.process()
assert m.current_state.is_success and not m.current_state.is_error

Does this work for you?

lakenn commented 4 years ago

ic, thanks for the example.