pytransitions / transitions

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

feature: expect_override decorator to mark model methods safe for overriding #676

Closed aleneum closed 2 weeks ago

aleneum commented 2 weeks ago

As of now, transition will not decorate models with trigger and convenience functions if they are already defined on the model. The check is done in Machine._checked_assignment. Users had to override _checked_assignment if they wanted to define model methods (e.g. for type checking) and have them overridden by transitions during runtime. This approach is an all or nothing solution. With expect_override, transitions now features an approach where developers can explicitly mark model methods that are intended to be overriden.

from transitions import Machine
from transitions.experimental.decoration import expect_override

class Model:

    @expect_override
    def is_A(self) -> bool:  # will be overridden during initialisation of Machine
        raise RuntimeError("Should be overridden")

    def is_B(self) -> bool:  # will NOT be overridden
        return False

    @expect_override
    def is_C(self) -> bool:  # will be overridden when state C is added later on
        return False

model = Model()

machine = Machine(model, states=["A", "B"], initial="A")

This is a step in the effort to improve the typing support of transitions.

Some related issues:

coveralls commented 2 weeks ago

Coverage Status

coverage: 98.528% (+0.002%) from 98.526% when pulling 17b4ca16605a374ac51e7fc11d921bc438bb6616 on dev-experimental-decorator into 4a3f06a5cfe1f63fae0dd0b87147208cf716bd65 on master.