Skip to content

Conversation

@rodrigobnogueira
Copy link

This PR adds Generic support to StateMachine so type checkers can properly infer the model type.

Closes #515

What changed

  • Added GenericStateMachineMetaclass that combines the existing metaclass with type(Generic)
  • Made StateMachine inherit from Generic[TModel]
  • Updated type hints for the model parameter and attribute
  • Added tests for the new functionality

Why this is useful

Before this change, sm.model was typed as Any, which meant no autocomplete and no type checking for model attributes. Now you can do:

class MyModel:
    def __init__(self):
        self.state = None
        self.custom_field = "test"

class MyMachine(StateMachine[MyModel]):
    initial = State("Initial", initial=True)
    final = State("Final", final=True)
    go = initial.to(final)

sm = MyMachine(model=MyModel())
sm.model.custom_field  # type checker knows this exists

This implements Generic support for the StateMachine class, enabling
type checkers to infer the correct type of the model attribute.

Changes:
- Add TModel TypeVar and GenericStateMachineMetaclass in factory.py
- Update StateMachine to inherit from Generic[TModel]
- Update type hints: model parameter and attribute
- Add comprehensive test suite with 6 new tests

Benefits:
- Type checkers (mypy, pyright, pylance) can now validate model attributes
- IDE autocomplete works correctly for model.attribute access
- Fully backward compatible with existing non-generic code
- Catches attribute errors at type-check time instead of runtime

Testing:
- 119 core tests passing (including 6 new Generic support tests)
- 304 total tests passing
- Validated on Python 3.10 and 3.11
- mypy type checking passes without errors

Closes fgmacedo#515
@sonarqubecloud
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Development Bug: pyright and other language servers cannot identify unresolved references on subclasses of StateMachine

1 participant