fix(event): type rx.event handlers as EventCallback under mypy

Merged
VJ
1mo ago
+29-27

Summary

Under mypy, every @rx.event handler is typed as EventNamespace, so calling one directly fails with "EventNamespace" not callable [operator]. Pyright infers EventCallback[...], so CI doesn't catch it.

The issue suggests mypy ignores the __new__ return type. The cause is a bit narrower. mypy does honor a __new__ return type that isn't the class, but here it can't resolve that type at all. EventNamespace re-exports the event classes as plain class attributes (EventCallback = EventCallback). Inside the class body, EventCallback[*P] in the __new__ overloads refers to that class attribute. mypy treats a class-level X = X as a variable, not a type alias. The return type stays unresolved (reveal_type(rx.event) shows -> EventCallback?[Any]), and mypy falls back to EventNamespace.

Change:

  • Annotate the type re-exports in EventNamespace as TypeAlias (EventCallback: TypeAlias = EventCallback, and so on for the classes and TypeAliasTypes). mypy then resolves them as types.
  • Side effect: annotations through the namespace, such as -> rx.event.EventSpec, now work under mypy too. That pattern appears in the docs and in reflex-components-internal. It used to fail with Variable "reflex_base.event.EventNamespace.EventSpec" is not valid as a type.
  • No runtime change: each attribute still holds the same object.

Verification

  • The reproduction from the issue under mypy --strict (mypy 2.4.0):
    • Before: "EventNamespace" not callable on s.bump(2) and await s.load(), and reveal_type(S.bump) is EventNamespace.
    • After: no errors, and reveal_type(S.bump) is EventCallback[int].
  • tests/type_checking/event.py already holds the assert_type contract for handlers. Under mypy it had 30 errors on main and has none with this change. The other files in tests/type_checking have 7 mypy errors (fields.py, vars.py), the same on main and unrelated. mypy isn't one of the checkers wired into pre-commit, so I didn't add a hook. I'm happy to add one scoped to event.py if you'd like a mypy guard.
  • uv run pyright reflex tests packages/reflex-base: the error list is identical before and after (58 pre-existing, all Windows-only such as os.fork / signal.SIGKILL on my machine).
  • ty check --python-version 3.14 tests/type_checking: passes.
  • uv run pytest tests/units/reflex_base/event tests/units/test_event.py tests/units/test_state.py: 890 passed.
  • pre-commit (ruff, codespell, update-pyi-files, pyright, ty) passes on the changed files.
  • Added the news fragment packages/reflex-base/news/7709.bugfix.md.

Closes #7709