pytransitions / transitions

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

after_state_change not triggered by set_state #638

Closed louisjmorgan closed 8 months ago

louisjmorgan commented 8 months ago

Describe the bug

The after_state_change callback seems to only be triggered by transitions, and not by manually setting the state. This can't be feature, so I can only assume it's a bug.

Minimal working example

def info():
    print("changed")

machine = Machine(
    states=["initial", "test"],
    transitions=[["test", "initial", "test"]],
    initial="initial",
    after_state_change=info)

machine.test()  # prints "changed"
print(machine.state)
machine.set_state("initial")  # doesn't print changed
print(machine.state)

output:

changed
test
initial

Expected behavior

I expect changing the state to trigger the after_state_change callback, because the state has changed.

aleneum commented 8 months ago

Hi @louisjmorgan,

as of now, this is expected behaviour. set_state just simply assigns a state to a model (as in it assigns a value to the model's state attribute which is commonly called 'state') but does not trigger any callbacks. You could use the default auto transitions which more or less have the same effect but process state-related callbacks such as after_state_change.

# instead of machine.set_state("initial")
machine.to_initial()
louisjmorgan commented 8 months ago

Fair enough. I think after_state_change should be called something else in that case, but I understand.