Skip to content

fix: Add return type annotations for async-compatible methods#545

Closed
rodrigobnogueira wants to merge 1 commit intofgmacedo:developfrom
rodrigobnogueira:feature/generic-model-support
Closed

fix: Add return type annotations for async-compatible methods#545
rodrigobnogueira wants to merge 1 commit intofgmacedo:developfrom
rodrigobnogueira:feature/generic-model-support

Conversation

@rodrigobnogueira
Copy link
Contributor

@rodrigobnogueira rodrigobnogueira commented Dec 26, 2025

Methods activate_initial_state(), send(), _processing_loop(), and Event.__call__() can return a coroutine when AsyncEngine is active, but their type signatures did not reflect this, causing type checkers to report Type 'bool' is not awaitable errors.

What changed

Added -> Any return type annotation to:

  • run_async_from_sync() in utils.py
  • activate_initial_state() in statemachine.py
  • _processing_loop() in statemachine.py
  • send() in statemachine.py
  • Event.__call__() in event.py

Minimal reproduction

class MyMachine(StateMachine):
    initial = State(initial=True)
    final = State(final=True)
    go = initial.to(final)

    # This single async callback forces AsyncEngine
    async def on_enter_final(self) -> None:
        pass
async def main() -> None:
    sm = MyMachine()
    await sm.activate_initial_state()  # ← type error before fix
    await sm.send("go")               # ← type error before fix

@sonarqubecloud
Copy link

@fgmacedo
Copy link
Owner

Hey @rodrigo-nogueira, thanks for taking the time to put this together — I appreciate the effort and the focus on improving type safety!

After reviewing the changes, I've decided not to merge this as-is. Here's my detailed feedback:

Doesn't address #515

The root cause of #515 (Pyright not detecting unresolved references on StateMachine subclasses) is the __getattr__ catch-all in the metaclass:

if TYPE_CHECKING:
    def __getattr__(self, attribute: str) -> Any: ...

This tells type checkers that any attribute exists and returns Any, which suppresses all unresolved reference warnings. The Generic[TModel] support only improves typing of sm.model, which is a different (and valid) concern, but doesn't fix the reported issue.

GenericStateMachineMetaclass is unnecessary

type(Generic) is just type, and StateMachineMetaclass already inherits from type. I've confirmed that class StateMachine(Generic[T], metaclass=StateMachineMetaclass) works directly — no combined metaclass needed.

type: ignore[assignment] hides a real type mismatch

When model=None, assigning Model() to self.model: TModel is incorrect from the type checker's perspective. This would need @overload on __init__ to properly express the two signatures (with and without a model).

Unrelated formatting changes

The diff includes several line-wrapping reformats that are unrelated to the feature, which adds noise to the review.


That said, I do think Generic model support is a valuable feature. I plan to revisit this along with broader type safety improvements (including the __getattr__ issue from #515) in the next major version (3.0), where we can make more deliberate changes to the type surface.

Thanks again for the contribution and for bringing attention to this!

@rodrigobnogueira
Copy link
Contributor Author

Thanks @fgmacedo , you're right. I was about to revisit this one. Sorry about the mess.

I was working in a project and we needed to make type checkers happy.

Minimal reproduction:

class MyMachine(StateMachine):
    initial = State(initial=True)
    final = State(final=True)
    go = initial.to(final)

    # This single async callback forces AsyncEngine
    async def on_enter_final(self) -> None:
        pass
async def main() -> None:
    sm = MyMachine()
    await sm.activate_initial_state()  # ← type error
    await sm.send("go")               # ← type error
    assert sm.current_state == sm.final

Type checkers (pyright, mypy) report: Type 'bool' is not awaitable

The root cause is that activate_initial_state() and send() are regular def methods, but when AsyncEngine is active, they return a coroutine via run_async_from_sync(). The await is correct at runtime, the type signatures just don't reflect it.

Methods activate_initial_state(), send(), _processing_loop(), and
Event.__call__() can return a coroutine when AsyncEngine is active,
but their type signatures did not reflect this, causing type checkers
to report 'Type bool is not awaitable' errors.

Add -> Any return type to these methods and to run_async_from_sync()
so type checkers allow await on the return values.
@rodrigobnogueira rodrigobnogueira force-pushed the feature/generic-model-support branch from fadfc88 to b659163 Compare February 13, 2026 22:26
@sonarqubecloud
Copy link

@rodrigobnogueira rodrigobnogueira changed the title feat: Add Generic[TModel] support for type-safe model attribute fix: Add return type annotations for async-compatible methods Feb 13, 2026
@codecov
Copy link

codecov bot commented Feb 13, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.77%. Comparing base (9a089ed) to head (b659163).
⚠️ Report is 20 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #545      +/-   ##
===========================================
- Coverage   100.00%   99.77%   -0.23%     
===========================================
  Files           25       25              
  Lines         1631     1758     +127     
  Branches       257      230      -27     
===========================================
+ Hits          1631     1754     +123     
- Misses           0        2       +2     
- Partials         0        2       +2     
Flag Coverage Δ
unittests 99.77% <100.00%> (-0.23%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@rodrigobnogueira
Copy link
Contributor Author

Sorry for the messy history on this one.

I've rebased the branch, dropped the Generic[TModel] commits and kept only the async type annotation fix for the minimal reproduction in the previous message. I still don't know if -> Any is the best solution, but it works and all tests pass.

Feel free to close this if you'd prefer a different approach, and let me know if I can help with anything else.

Thanks 🙏👍

@fgmacedo
Copy link
Owner

Thanks @rodrigobnogueira , closing in favor of #566

@fgmacedo fgmacedo closed this Feb 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments