Python

Python: StateMachine 콜백 함수 # state에 따른 콜백 # transition에 따른 콜백

taltal 2025. 6. 4. 23:08
728x90
반응형

python-statemachine 에서 콜백 함수의 동작 순서 정리

 

 

from statemachine import StateMachine


class TestSM(StateMachine):
    # 상태 정의
    idle = State("Idle", initial=True)
    error = State("Error")

    # 상태 전의 정의
    start_error_init = idle.to(error)

    def on_enter_error(self):
        print("idle to error")
  
    def on_exit_idle(self):
        print("exited from idle")

    def on_start_error_init(self):
        print("Executed before transition (idle to error by transition definition)")
        
    def after_start_error_init(self):
        print("Executed after transition (idle to error by transition definition)")

 

on_enter_ , on_exit

특정 상태로 진입하거나 빠져나올 때 동작하는 콜백함수이다.

 

transition이 일어날때도 위와 같은 방식의 콜백이 사용이 가능한데, 위 코드에서 on_start_error_init과 after_start_error_init이 이에 해당한다.

on_, after_

 

transition 콜백과 관련하여 헷갈리면 안될 부분이 동작 순서이다.

예를 들어서 동작 transition을 정의한 것을 통해 상태를 변화 시킬시(start_error_init() 을 통해)

다음과 같은 방식으로 콜백 함수가 동작한다.

 

idle  --> on_start_error_init()-->  error --> after_start_error_init()

 

즉, on_start_error_init에서는 이전 상태가 그대로 유지되어 있는 상태기 때문에,

상태 값에 따라 동작하는 코드가 들어간다면 주의해야 한다. (이를 인지하지 못해 시간을 좀 허비했다..)

 

 

728x90
반응형