pytransitions / transitions

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

How can I return data from a callback? #528

Closed Kaju-Bubanja closed 3 years ago

Kaju-Bubanja commented 3 years ago

I have some states and can pass data in nicely, now a use case came up where I need to return some data from a callback to the caller of the transition function, is there a way to do that?

aleneum commented 3 years ago

Hello @Kaju-Bubanja,

model triggers can only return True for a successful and False for a 'failed' transition. If you need to pass data around, consider model attributes or arguments passed by reference to callbacks (like dictionaries):

from transitions import Machine

class Model:

    def __init__(self):
        self.completion = 0

    def calc_value(self, current_state=None):
        if current_state is not None:
            current_state["completion"] += 25
            self.completion = current_state["completion"]
        else:
            self.completion += 25

    def is_done(self, current_state=None):
        progress = current_state["completion"] if current_state is not None else self.completion
        return progress >= 100

transitions = [
    {"trigger": "progress", "source": ["Init", "Pending"], "dest": "Done", "prepare": "calc_value",
     "conditions": "is_done"}
]

model = Model()
machine = Machine(model=model, states=['Init', 'Pending', 'Done'], transitions=transitions, initial='Init')

model.progress()
model.progress()
assert model.completion == 50

current_state = {"completion": model.completion}
model.progress(current_state)
assert current_state["completion"] == 75
model.progress(current_state)
assert model.is_Done()
aleneum commented 3 years ago

closing this since there has been no feedback within 2 weeks. Feel free if the issue still persists. I will reopen the issue if necessary.