fix: support type(self) event chaining in background tasks
Note: #7313 (merged Dec 3) removed StateProxy, and with it this bug: background tasks now get the plain state, so type(self) is the state class. Our regression test below passes unchanged on current main (333785af2) without this fix. This branch was built on c398e8207, before #7313 landed, so it conflicts with main in reflex/istate/proxy.py and docs/events/background_events.md.
We're opening it so the work is visible. If the tests are still useful to you, we're happy to reduce this to the regression and Playwright tests on the new layout, so #4947 can be closed with coverage that keeps it fixed.
All Submissions:
- Have you followed the guidelines stated in CONTRIBUTING.md file?
- Have you checked to ensure there aren't any other open Pull Requests for the desired changed?
Why
A background handler got a StateProxy as self, so type(self) was StateProxy, and yield type(self).handler(...) raised AttributeError: type object 'StateProxy' has no attribute 'handler' (#4947).
What changed
reflex/istate/proxy.py: a proxy subclass is generated and cached per proxy kind (StateProxy,ReadOnlyStateProxy) and wrapped state class. Its metaclass forwards missing class attributes to the state class, as suggested on the issue. The proxiesStateProxybuilds for other states (_call_on_ancestor, the router root, inherited mutable fields,get_state) take the class of the state they wrap, and are initialized explicitly when Python skips__init__.tests/units/test_state.py: regression chainingtype(self).event_arg(4)and(5)from a background handler, checking the full event order.tests/units/istate/test_proxy.py: class-level lookup for own, inherited and overridden handlers and vars, one class per state class, ancestor andget_stateproxies, and a mixin background handler chaining throughtype(self).tests/integration/tests_playwright/test_background_task.py: browser tests for chaining throughtype(self)in a running app.- Docs for background events and the 0.10 upgrade note, and
news/+stateproxy-type-self.bugfix.md.
How tested
- The regression and compatibility tests fail on
c398e8207with theAttributeErrorabove and pass with the fix. - On this branch,
tests/unitspasses with 83% coverage, and the Playwright tests pass. ruff check,ruff format,pyrightand the other pre-commit hooks are clean.
Known limits
issubclass(type(self), SomeState)stays false, and names already defined on the proxy class (get_state,__name__) are not forwarded.
Type of change
- Bug fix (non-breaking change which fixes an issue)
Related: #4947