pytransitions / transitions

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

Pass eventData to condition #561

Closed aurelien78 closed 2 years ago

aurelien78 commented 2 years ago

Hi,

First, thanks a lot for your work. My request : would it be possible to pass eventData to condition also ?

Thanks a lot.

aleneum commented 2 years ago

The documentation states:

If you set send_event=True at Machine initialization, all arguments to the triggers will be wrapped in an EventData instance and passed on to every callback.

Since conditions are also callbacks, you get event data just like in other callbacks like before etc.

from transitions import Machine, EventData

class Model:

    def has_element(self, event_data: EventData) -> bool:
        return "element" in event_data.kwargs

model = Model()
machine = Machine(model, states=["A", "B"], initial="A", send_event=True,
                  transitions=[dict(trigger="go", source="A", dest="B", conditions="has_element")])

assert model.is_A()
assert not model.go()
assert model.is_A()
assert model.go(element=1)
assert model.is_B()

I will close this issue since it seems to be a question about how to use transitions since the feature you request is already implemented. Feel free to comment anyway. I will open the issue again if necessary.

aurelien78 commented 2 years ago

Thanks a lot. For information, I had a problem using event as parameters since I left @property declaration : @property def condition(self, event) -> bool: return True Doesn't work

Removing @property and then ok !