From bcb33f062d48c31e876b43373f0fe8621375c096 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 19 Nov 2026 21:28:36 +0100 Subject: [PATCH 1/4] feat: typed access to dynamic route args with rx.State.route_arg Adding a page at `/post/[pid]` installs `rx.State.pid` at runtime, so type checkers do not know the attribute and code using it needs an ignore. `rx.State.route_arg("pid")` returns the same var as a `StringVar`, and `rx.State.route_arg("splat")` the one of the `[[...splat]]` catch-all as an `ArrayVar[list[str]]`. An arg no added page declares raises DynamicRouteArgNotFoundError. Co-Authored-By: Claude Opus 5.5 --- docs/pages/dynamic_routing.md | 6 ++++ news/+typed-route-arg.feature.md | 1 + .../news/+typed-route-arg.feature.md | 1 + .../src/reflex_base/utils/exceptions.py | 4 +++ reflex/state.py | 35 +++++++++++++++++++ tests/type_checking/state.py | 12 +++++++ tests/units/test_app.py | 21 +++++++++++ 7 files changed, 80 insertions(+) create mode 100644 news/+typed-route-arg.feature.md create mode 100644 packages/reflex-base/news/+typed-route-arg.feature.md create mode 100644 tests/type_checking/state.py diff --git a/docs/pages/dynamic_routing.md b/docs/pages/dynamic_routing.md index 5484c0e3323..a70762eb85f 100644 --- a/docs/pages/dynamic_routing.md +++ b/docs/pages/dynamic_routing.md @@ -18,6 +18,12 @@ Regular dynamic routes in Reflex allow you to match specific segments in a URL d The dynamic route arguments are accessible as `rx.State.id` and `rx.State.category` here as the var is added to the root state, so that it is accessible from any state. ``` +```md alert info +# Accessing a dynamic route argument with type checking + +The var is added to the root state when the page is added, so type checkers do not know `rx.State.id`. `rx.State.route_arg("id")` returns the same var as a `StringVar`, and `rx.State.route_arg("splat")` the one of a catch-all route as an `ArrayVar[list[str]]`. +``` + Example: ```python diff --git a/news/+typed-route-arg.feature.md b/news/+typed-route-arg.feature.md new file mode 100644 index 00000000000..52b70cb8c27 --- /dev/null +++ b/news/+typed-route-arg.feature.md @@ -0,0 +1 @@ +Add `rx.State.route_arg(name)`, which returns the var of a page's dynamic route argument with a type: a `StringVar` for `[name]`, an `ArrayVar[list[str]]` for the `[[...splat]]` catch-all. Type checkers do not know `rx.State.name`, which is only added with the page. diff --git a/packages/reflex-base/news/+typed-route-arg.feature.md b/packages/reflex-base/news/+typed-route-arg.feature.md new file mode 100644 index 00000000000..33244e15f87 --- /dev/null +++ b/packages/reflex-base/news/+typed-route-arg.feature.md @@ -0,0 +1 @@ +Add `DynamicRouteArgNotFoundError`, raised by `rx.State.route_arg` for a dynamic route argument that no added page declares. diff --git a/packages/reflex-base/src/reflex_base/utils/exceptions.py b/packages/reflex-base/src/reflex_base/utils/exceptions.py index 75368add0eb..ccef148ffff 100644 --- a/packages/reflex-base/src/reflex_base/utils/exceptions.py +++ b/packages/reflex-base/src/reflex_base/utils/exceptions.py @@ -214,6 +214,10 @@ class DynamicRouteArgShadowsStateVarError(ReflexError, NameError): """Raised when a dynamic route arg shadows a state var.""" +class DynamicRouteArgNotFoundError(ReflexError, AttributeError): + """Raised when a dynamic route arg is requested that no added page declares.""" + + class ComputedVarShadowsStateVarError(ReflexError, NameError): """Raised when a computed var shadows a state var.""" diff --git a/reflex/state.py b/reflex/state.py index 51934fe3e97..56c56866770 100644 --- a/reflex/state.py +++ b/reflex/state.py @@ -23,6 +23,7 @@ Any, BinaryIO, ClassVar, + Literal, ParamSpec, Self, TypeVar, @@ -48,6 +49,7 @@ from reflex_base.registry import RegistrationContext from reflex_base.utils.exceptions import ( DynamicComponentInvalidSignatureError, + DynamicRouteArgNotFoundError, DynamicRouteArgShadowsStateVarError, ReflexRuntimeError, SetUndefinedStateVarError, @@ -140,6 +142,7 @@ def _stale_pickle_keys(cls: type[BaseState]) -> frozenset[str]: if TYPE_CHECKING: from reflex_base.components.component import Component + from reflex_base.vars.sequence import ArrayVar, StringVar var = computed_var @@ -1668,6 +1671,38 @@ def inner_func(self: BaseState) -> list[str]: cls.vars.update(dynamic_vars) cls._update_substate_vars(dynamic_vars) + @overload + @classmethod + def route_arg(cls, name: Literal["splat"]) -> ArrayVar[list[str]]: ... # pyright: ignore[reportOverlappingOverload] + + @overload + @classmethod + def route_arg(cls, name: str) -> StringVar: ... + + @classmethod + def route_arg(cls, name: str) -> StringVar | ArrayVar[list[str]]: + """Get the var of a dynamic route arg, typed. + + Adding a page at ``/post/[pid]`` installs the var ``rx.State.pid``. Type + checkers cannot see that attribute, which only exists once the page is + added; ``rx.State.route_arg("pid")`` returns the same var as a + ``StringVar``, and ``rx.State.route_arg("splat")`` the one of a + ``[[...splat]]`` catch-all as an ``ArrayVar[list[str]]``. + + Args: + name: The name of the dynamic route arg, ``"splat"`` for the catch-all. + + Returns: + The var of the dynamic route arg. + + Raises: + DynamicRouteArgNotFoundError: If no added page declares the arg. + """ + if not isinstance(cls.vars.get(name), DynamicRouteVar): + msg = f"No page added so far declares the dynamic route arg {name!r}." + raise DynamicRouteArgNotFoundError(msg) + return getattr(cls, name) + if TYPE_CHECKING or environment.REFLEX_ENV_MODE.get() != constants.Env.PROD: def __setattr__(self, name: str, value: Any): diff --git a/tests/type_checking/state.py b/tests/type_checking/state.py new file mode 100644 index 00000000000..87d35dc2f16 --- /dev/null +++ b/tests/type_checking/state.py @@ -0,0 +1,12 @@ +"""Inferred types for `reflex.state` that are part of the public contract.""" + +from typing import assert_type + +import reflex as rx +from reflex.vars.sequence import ArrayVar, StringVar + +# `rx.State.pid` only exists once a page at `/post/[pid]` is added, so type +# checkers cannot see it; `route_arg` returns the same var, typed. The catch-all +# of a route is always named `splat` and holds the remaining segments. +assert_type(rx.State.route_arg("pid"), StringVar) +assert_type(rx.State.route_arg("splat"), ArrayVar[list[str]]) diff --git a/tests/units/test_app.py b/tests/units/test_app.py index def677fa646..37bbb0a2d05 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -46,6 +46,7 @@ from reflex_base.utils.imports import ImportVar from reflex_base.utils.types import ASGIApp, Receive, Scope, Send from reflex_base.vars.base import computed_var +from reflex_base.vars.sequence import ArrayVar, StringVar from reflex_components_core.base.bare import Bare from reflex_components_core.base.fragment import Fragment from reflex_components_core.core import _upload as upload_module @@ -370,6 +371,26 @@ def test_add_page_set_route_dynamic(index_page: ComponentCallable): assert "rx_router_page" in app._state()._var_dependencies +def test_route_arg(index_page: ComponentCallable): + """Get the vars of a page's dynamic route args through route_arg. + + Args: + index_page: The index page. + """ + app = App(_state=EmptyState) + assert app._state is not None + app.add_page(index_page, route="/route-arg/[dynamic]/[[...splat]]") + + # the same vars as the attributes the page added, e.g. `EmptyState.dynamic` + for name, var_cls in (("dynamic", StringVar), ("splat", ArrayVar)): + var = app._state.route_arg(name) + assert isinstance(var, var_cls) + assert var._js_expr == getattr(app._state, name)._js_expr + + with pytest.raises(exceptions.DynamicRouteArgNotFoundError, match="not_added"): + app._state.route_arg("not_added") + + def test_add_page_set_route_nested(app: App, index_page: ComponentCallable): """Test adding a page to an app. From 67b6c162bacb3523b5ab4ff555df5097c5f037f5 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 19 Nov 2026 21:40:36 +0100 Subject: [PATCH 2/4] Split the catch-all into route_catch_all, floor reflex-base, compare full errors The name alone does not decide a route arg's type: `/post/[splat]` is a regular arg named `splat`, so `route_arg(Literal["splat"])` promised an ArrayVar for a StringVar, and `route_arg(name: str)` a StringVar for the catch-all when called with a `str` that is "splat". `route_arg(name)` is now the regular arg as a StringVar and `route_catch_all()` the `[[...splat]]` catch-all as an ArrayVar[list[str]]; each checks the installed arg is of its kind. reflex imports DynamicRouteArgNotFoundError from the unreleased reflex-base, so its floor is reflex-base >= 0.11.1.dev0. The tests compare the complete error messages. Co-Authored-By: Claude Opus 5.5 --- docs/pages/dynamic_routing.md | 2 +- news/+typed-route-arg.feature.md | 2 +- .../news/+typed-route-arg.feature.md | 2 +- .../src/reflex_base/utils/exceptions.py | 2 +- pyproject.toml | 2 +- reflex/state.py | 62 ++++++++++++++----- tests/type_checking/state.py | 6 +- tests/units/test_app.py | 45 +++++++++++--- 8 files changed, 92 insertions(+), 31 deletions(-) diff --git a/docs/pages/dynamic_routing.md b/docs/pages/dynamic_routing.md index a70762eb85f..ff2a083ab4f 100644 --- a/docs/pages/dynamic_routing.md +++ b/docs/pages/dynamic_routing.md @@ -21,7 +21,7 @@ The dynamic route arguments are accessible as `rx.State.id` and `rx.State.catego ```md alert info # Accessing a dynamic route argument with type checking -The var is added to the root state when the page is added, so type checkers do not know `rx.State.id`. `rx.State.route_arg("id")` returns the same var as a `StringVar`, and `rx.State.route_arg("splat")` the one of a catch-all route as an `ArrayVar[list[str]]`. +The var is added to the root state when the page is added, so type checkers do not know `rx.State.id`. `rx.State.route_arg("id")` returns the same var as a `StringVar`, and `rx.State.route_catch_all()` the one of a catch-all route as an `ArrayVar[list[str]]`. ``` Example: diff --git a/news/+typed-route-arg.feature.md b/news/+typed-route-arg.feature.md index 52b70cb8c27..2bac8ae494d 100644 --- a/news/+typed-route-arg.feature.md +++ b/news/+typed-route-arg.feature.md @@ -1 +1 @@ -Add `rx.State.route_arg(name)`, which returns the var of a page's dynamic route argument with a type: a `StringVar` for `[name]`, an `ArrayVar[list[str]]` for the `[[...splat]]` catch-all. Type checkers do not know `rx.State.name`, which is only added with the page. +Add `rx.State.route_arg(name)` and `rx.State.route_catch_all()`, which return the var of a page's dynamic route argument with a type: a `StringVar` for `[name]`, an `ArrayVar[list[str]]` for the `[[...splat]]` catch-all. Type checkers do not know `rx.State.name`, which is only added with the page. diff --git a/packages/reflex-base/news/+typed-route-arg.feature.md b/packages/reflex-base/news/+typed-route-arg.feature.md index 33244e15f87..82037c3f88d 100644 --- a/packages/reflex-base/news/+typed-route-arg.feature.md +++ b/packages/reflex-base/news/+typed-route-arg.feature.md @@ -1 +1 @@ -Add `DynamicRouteArgNotFoundError`, raised by `rx.State.route_arg` for a dynamic route argument that no added page declares. +Add `DynamicRouteArgNotFoundError`, raised by `rx.State.route_arg` and `rx.State.route_catch_all` for a dynamic route argument that no added page declares as such. diff --git a/packages/reflex-base/src/reflex_base/utils/exceptions.py b/packages/reflex-base/src/reflex_base/utils/exceptions.py index ccef148ffff..9f13a982d0b 100644 --- a/packages/reflex-base/src/reflex_base/utils/exceptions.py +++ b/packages/reflex-base/src/reflex_base/utils/exceptions.py @@ -215,7 +215,7 @@ class DynamicRouteArgShadowsStateVarError(ReflexError, NameError): class DynamicRouteArgNotFoundError(ReflexError, AttributeError): - """Raised when a dynamic route arg is requested that no added page declares.""" + """Raised when a dynamic route arg is requested that no added page declares as such.""" class ComputedVarShadowsStateVarError(ReflexError, NameError): diff --git a/pyproject.toml b/pyproject.toml index 59f3c764b7c..fca2974cf61 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -33,7 +33,7 @@ dependencies = [ "starlette >=1.3.1", "typing_extensions >=4.13.0", "wrapt >=1.17.0,<2.6", - "reflex-base >= 0.10.2.dev0", + "reflex-base >= 0.11.1.dev0", "reflex-components-code >= 0.11.0", "reflex-components-core >= 0.11.0", "reflex-components-dataeditor >= 0.10.1", diff --git a/reflex/state.py b/reflex/state.py index 56c56866770..522502aeabd 100644 --- a/reflex/state.py +++ b/reflex/state.py @@ -23,7 +23,6 @@ Any, BinaryIO, ClassVar, - Literal, ParamSpec, Self, TypeVar, @@ -1671,37 +1670,68 @@ def inner_func(self: BaseState) -> list[str]: cls.vars.update(dynamic_vars) cls._update_substate_vars(dynamic_vars) - @overload @classmethod - def route_arg(cls, name: Literal["splat"]) -> ArrayVar[list[str]]: ... # pyright: ignore[reportOverlappingOverload] + def _installed_route_arg(cls, name: str, arg_type: str, kind: str) -> Any: + """Get the var a page installed for a dynamic route arg of the given type. - @overload - @classmethod - def route_arg(cls, name: str) -> StringVar: ... + Args: + name: The name of the dynamic route arg. + arg_type: The ``RouteArgType`` the arg must have. + kind: How the arg appears in a route, for the error message. + + Returns: + The var of the dynamic route arg, as class access returns it. + + Raises: + DynamicRouteArgNotFoundError: If no added page declares the arg as `kind`. + """ + var = cls.vars.get(name) + if not isinstance(var, DynamicRouteVar): + msg = f"No page added so far declares the dynamic route arg {kind}." + raise DynamicRouteArgNotFoundError(msg) + installed = ( + constants.RouteArgType.LIST + if var._var_type == list[str] + else constants.RouteArgType.SINGLE + ) + if installed != arg_type: + msg = f"The pages added so far declare `{name}`, but not as {kind}." + raise DynamicRouteArgNotFoundError(msg) + return getattr(cls, name) @classmethod - def route_arg(cls, name: str) -> StringVar | ArrayVar[list[str]]: + def route_arg(cls, name: str) -> StringVar: """Get the var of a dynamic route arg, typed. Adding a page at ``/post/[pid]`` installs the var ``rx.State.pid``. Type checkers cannot see that attribute, which only exists once the page is added; ``rx.State.route_arg("pid")`` returns the same var as a - ``StringVar``, and ``rx.State.route_arg("splat")`` the one of a - ``[[...splat]]`` catch-all as an ``ArrayVar[list[str]]``. + ``StringVar``. The ``[[...splat]]`` catch-all is ``route_catch_all()``. Args: - name: The name of the dynamic route arg, ``"splat"`` for the catch-all. + name: The name of the dynamic route arg. Returns: The var of the dynamic route arg. + """ + return cls._installed_route_arg( + name, constants.RouteArgType.SINGLE, f"[{name}]" + ) - Raises: - DynamicRouteArgNotFoundError: If no added page declares the arg. + @classmethod + def route_catch_all(cls) -> ArrayVar[list[str]]: + """Get the var of the ``[[...splat]]`` catch-all route arg, typed. + + Adding a page at ``/docs/[[...splat]]`` installs the var + ``rx.State.splat`` with the remaining path segments, which type checkers + cannot see; this returns the same var as an ``ArrayVar[list[str]]``. + + Returns: + The var of the catch-all route arg. """ - if not isinstance(cls.vars.get(name), DynamicRouteVar): - msg = f"No page added so far declares the dynamic route arg {name!r}." - raise DynamicRouteArgNotFoundError(msg) - return getattr(cls, name) + return cls._installed_route_arg( + "splat", constants.RouteArgType.LIST, constants.RouteRegex.SPLAT_CATCHALL + ) if TYPE_CHECKING or environment.REFLEX_ENV_MODE.get() != constants.Env.PROD: diff --git a/tests/type_checking/state.py b/tests/type_checking/state.py index 87d35dc2f16..10ed646c96a 100644 --- a/tests/type_checking/state.py +++ b/tests/type_checking/state.py @@ -6,7 +6,7 @@ from reflex.vars.sequence import ArrayVar, StringVar # `rx.State.pid` only exists once a page at `/post/[pid]` is added, so type -# checkers cannot see it; `route_arg` returns the same var, typed. The catch-all -# of a route is always named `splat` and holds the remaining segments. +# checkers cannot see it; `route_arg` returns the same var, typed, and +# `route_catch_all` the one of a `[[...splat]]` catch-all. assert_type(rx.State.route_arg("pid"), StringVar) -assert_type(rx.State.route_arg("splat"), ArrayVar[list[str]]) +assert_type(rx.State.route_catch_all(), ArrayVar[list[str]]) diff --git a/tests/units/test_app.py b/tests/units/test_app.py index 37bbb0a2d05..304fd8cb3a7 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -372,7 +372,7 @@ def test_add_page_set_route_dynamic(index_page: ComponentCallable): def test_route_arg(index_page: ComponentCallable): - """Get the vars of a page's dynamic route args through route_arg. + """Get the vars of a page's dynamic route args through the typed accessors. Args: index_page: The index page. @@ -382,13 +382,44 @@ def test_route_arg(index_page: ComponentCallable): app.add_page(index_page, route="/route-arg/[dynamic]/[[...splat]]") # the same vars as the attributes the page added, e.g. `EmptyState.dynamic` - for name, var_cls in (("dynamic", StringVar), ("splat", ArrayVar)): - var = app._state.route_arg(name) - assert isinstance(var, var_cls) - assert var._js_expr == getattr(app._state, name)._js_expr - - with pytest.raises(exceptions.DynamicRouteArgNotFoundError, match="not_added"): + dynamic = app._state.route_arg("dynamic") + assert isinstance(dynamic, StringVar) + assert dynamic._js_expr == getattr(app._state, "dynamic")._js_expr # noqa: B009 + splat = app._state.route_catch_all() + assert isinstance(splat, ArrayVar) + assert splat._js_expr == getattr(app._state, "splat")._js_expr # noqa: B009 + + with pytest.raises(exceptions.DynamicRouteArgNotFoundError) as err: app._state.route_arg("not_added") + assert str(err.value) == ( + "No page added so far declares the dynamic route arg [not_added]." + ) + with pytest.raises(exceptions.DynamicRouteArgNotFoundError) as err: + app._state.route_arg("splat") + assert ( + str(err.value) == "The pages added so far declare `splat`, but not as [splat]." + ) + + +def test_route_catch_all_of_a_regular_arg(index_page: ComponentCallable): + """A regular arg named `splat` is no catch-all. + + Args: + index_page: The index page. + """ + + class RegularSplatState(BaseState): + """State whose only page has a regular `splat` arg.""" + + app = App(_state=RegularSplatState) + app.add_page(index_page, route="/regular-splat/[splat]") + + assert isinstance(RegularSplatState.route_arg("splat"), StringVar) + with pytest.raises(exceptions.DynamicRouteArgNotFoundError) as err: + RegularSplatState.route_catch_all() + assert str(err.value) == ( + "The pages added so far declare `splat`, but not as [[...splat]]." + ) def test_add_page_set_route_nested(app: App, index_page: ComponentCallable): From 0edfed47b77aeba595ce0bfcd1b541879d538867 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 19 Nov 2026 22:06:57 +0100 Subject: [PATCH 3/4] docs: give the route_catch_all sentence its verb Co-Authored-By: Claude Opus 5.5 --- docs/pages/dynamic_routing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/pages/dynamic_routing.md b/docs/pages/dynamic_routing.md index ff2a083ab4f..d80fa2b6892 100644 --- a/docs/pages/dynamic_routing.md +++ b/docs/pages/dynamic_routing.md @@ -21,7 +21,7 @@ The dynamic route arguments are accessible as `rx.State.id` and `rx.State.catego ```md alert info # Accessing a dynamic route argument with type checking -The var is added to the root state when the page is added, so type checkers do not know `rx.State.id`. `rx.State.route_arg("id")` returns the same var as a `StringVar`, and `rx.State.route_catch_all()` the one of a catch-all route as an `ArrayVar[list[str]]`. +The var is added to the root state when the page is added, so type checkers do not know `rx.State.id`. `rx.State.route_arg("id")` returns the same var as a `StringVar`, and `rx.State.route_catch_all()` returns the catch-all route's var as an `ArrayVar[list[str]]`. ``` Example: From 51c5592345958d0189a0c684aa302e1cc319e55a Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Sat, 21 Nov 2026 18:14:03 +0100 Subject: [PATCH 4/4] Replace the route arg classmethods with rx.route_arg and rx.route_catch_all `rx.State.route_arg` and `rx.State.route_catch_all` made both names framework members of every state: a state var or computed var named `route_arg`, an event handler named `route_catch_all`, or a page at `/x/[route_arg]` worked before and raised once they existed. The accessors are now the module-level functions `rx.route_arg(name)` and `rx.route_catch_all()`, resolved against `rx.State`, the only root state an app can have. They reserve no names. Their docstrings and the docs say that they return a var for building components, not the value in an event handler or a computed var. The docs show `rx.route_arg("pid")` in the `/post/[pid]` example, and the catch-all accessor moves to the Catch-All Routes section with an `rx.foreach(rx.route_catch_all(), rx.text)` example. The errors say what is installed and point to the other accessor. `_route_arg_type` classifies an installed route var for these and for `_dynamic_route_arg_types`, and `RouteRegex.SPLAT_ARG` names the catch-all arg for them and for `get_route_args`. The tests move to test_state.py, next to the code. They resolve the accessors against a fresh root state rather than `rx.State` or the shared `EmptyState`, compare the vars with `equals`, and cover a substate, an optional `[[lang]]` arg, the errors, and a state that declares `route_arg` and `route_catch_all`. Co-Authored-By: Claude Opus 5.5 --- docs/pages/dynamic_routing.md | 15 +- news/+typed-route-arg.feature.md | 2 +- .../news/+typed-route-arg.feature.md | 2 +- .../src/reflex_base/constants/route.py | 4 +- pyi_hashes.json | 2 +- reflex/__init__.py | 2 + reflex/route.py | 2 +- reflex/state.py | 160 ++++++++++-------- tests/type_checking/state.py | 8 +- tests/units/test_app.py | 52 ------ tests/units/test_state.py | 122 +++++++++++++ 11 files changed, 239 insertions(+), 132 deletions(-) diff --git a/docs/pages/dynamic_routing.md b/docs/pages/dynamic_routing.md index d80fa2b6892..ed6b1a30611 100644 --- a/docs/pages/dynamic_routing.md +++ b/docs/pages/dynamic_routing.md @@ -21,7 +21,7 @@ The dynamic route arguments are accessible as `rx.State.id` and `rx.State.catego ```md alert info # Accessing a dynamic route argument with type checking -The var is added to the root state when the page is added, so type checkers do not know `rx.State.id`. `rx.State.route_arg("id")` returns the same var as a `StringVar`, and `rx.State.route_catch_all()` returns the catch-all route's var as an `ArrayVar[list[str]]`. +The var is added to the root state when the page is added, so type checkers do not know `rx.State.id`. `rx.route_arg("id")` returns the same var as a `StringVar`. Like `rx.State.id`, it is a var for building components, not the value: an event handler or a computed var reads the value from the state as before. ``` Example: @@ -30,8 +30,9 @@ Example: @rx.page(route="/post/[pid]") def post(): """A page that updates based on the route.""" - # Displays the dynamic part of the URL, the post ID - return rx.heading(rx.State.pid, as_="h2") + # Displays the dynamic part of the URL, the post ID. `rx.route_arg("pid")` + # is `rx.State.pid`, typed. + return rx.heading(rx.route_arg("pid"), as_="h2") app = rx.App() @@ -89,6 +90,14 @@ app = rx.App() In this case, the `...splat` catch-all pattern captures any number of segments after `/users/`, allowing URLs like `/users/2/posts/john/` and `/users/1/posts/john/doe/` to match the route. +`rx.route_catch_all()` returns the catch-all var, `rx.State.splat`, as an `ArrayVar[list[str]]`. Like `rx.route_arg`, it is a var for building components, not the value: + +```python +@rx.page(route="/files/[[...splat]]") +def files(): + return rx.vstack(rx.foreach(rx.route_catch_all(), rx.text)) +``` + ```md alert # Catch-all routes must be named `splat` and be placed at the end of the URL pattern to ensure proper route matching. ``` diff --git a/news/+typed-route-arg.feature.md b/news/+typed-route-arg.feature.md index 2bac8ae494d..425f879d462 100644 --- a/news/+typed-route-arg.feature.md +++ b/news/+typed-route-arg.feature.md @@ -1 +1 @@ -Add `rx.State.route_arg(name)` and `rx.State.route_catch_all()`, which return the var of a page's dynamic route argument with a type: a `StringVar` for `[name]`, an `ArrayVar[list[str]]` for the `[[...splat]]` catch-all. Type checkers do not know `rx.State.name`, which is only added with the page. +Add `rx.route_arg(name)` and `rx.route_catch_all()`, which return the var of a page's dynamic route argument with a type that type checkers see, unlike `rx.State.name`: a `StringVar` for `[name]` and an `ArrayVar[list[str]]` for the `[[...splat]]` catch-all, for example `rx.heading(rx.route_arg("pid"))` on a page at `/post/[pid]`. diff --git a/packages/reflex-base/news/+typed-route-arg.feature.md b/packages/reflex-base/news/+typed-route-arg.feature.md index 82037c3f88d..90c7a7f6d05 100644 --- a/packages/reflex-base/news/+typed-route-arg.feature.md +++ b/packages/reflex-base/news/+typed-route-arg.feature.md @@ -1 +1 @@ -Add `DynamicRouteArgNotFoundError`, raised by `rx.State.route_arg` and `rx.State.route_catch_all` for a dynamic route argument that no added page declares as such. +Add `DynamicRouteArgNotFoundError`, raised by `rx.route_arg` and `rx.route_catch_all` for a dynamic route argument that no page added so far has as that kind. diff --git a/packages/reflex-base/src/reflex_base/constants/route.py b/packages/reflex-base/src/reflex_base/constants/route.py index 4c8606561eb..cdf76b69e38 100644 --- a/packages/reflex-base/src/reflex_base/constants/route.py +++ b/packages/reflex-base/src/reflex_base/constants/route.py @@ -82,7 +82,9 @@ class RouteRegex(SimpleNamespace): rf"{_OPENING_BRACKET * 2}{_DOT_DOT_DOT}({_ARG_NAME}){_CLOSING_BRACKET * 2}" ) - SPLAT_CATCHALL = "[[...splat]]" + # The name of the catch-all arg, and the only catch-all pattern allowed. + SPLAT_ARG = "splat" + SPLAT_CATCHALL = f"[[...{SPLAT_ARG}]]" SINGLE_SEGMENT = "__SINGLE_SEGMENT__" DOUBLE_SEGMENT = "__DOUBLE_SEGMENT__" DOUBLE_CATCHALL_SEGMENT = "__DOUBLE_CATCHALL_SEGMENT__" diff --git a/pyi_hashes.json b/pyi_hashes.json index 8f2b4c8aa7a..c171bd3b004 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,7 +118,7 @@ "packages/reflex-components-recharts/src/reflex_components_recharts/polar.pyi": "adc4db1a3ca7cd292b099ec4d97a4346", "packages/reflex-components-recharts/src/reflex_components_recharts/recharts.pyi": "f2a9cf6db58d169289fbc76de6813300", "packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "f170ac685b6ba5892370166c80684db3", - "reflex/__init__.pyi": "067a60e22fb825072f2f0b690662da5a", + "reflex/__init__.pyi": "d14b41f4d9f0ccf5c14fcf56dbaf8c21", "reflex/components/__init__.pyi": "9facd05a776d0641432696bbf8e34388", "reflex/experimental/memo.pyi": "0fc8eae24cd0def5ea9d8d66ce87206e" } diff --git a/reflex/__init__.py b/reflex/__init__.py index 75cb5a1328b..a663fdb6b92 100644 --- a/reflex/__init__.py +++ b/reflex/__init__.py @@ -221,6 +221,8 @@ "ComponentState", "State", "dynamic", + "route_arg", + "route_catch_all", ], "istate.shared": ["SharedState"], "istate.wrappers": ["get_state"], diff --git a/reflex/route.py b/reflex/route.py index cfed5aa55d8..dd0a5612b4d 100644 --- a/reflex/route.py +++ b/reflex/route.py @@ -80,7 +80,7 @@ def _add_route_arg(arg_name: str, type_: str): # Iterate over the route parts and check for route args. for part in route.split("/"): if part == constants.RouteRegex.SPLAT_CATCHALL: - _add_route_arg("splat", constants.RouteArgType.LIST) + _add_route_arg(constants.RouteRegex.SPLAT_ARG, constants.RouteArgType.LIST) break optional_argument = optional_argument_regex.match(part) diff --git a/reflex/state.py b/reflex/state.py index 522502aeabd..3caf7abf256 100644 --- a/reflex/state.py +++ b/reflex/state.py @@ -419,6 +419,22 @@ def _bind_attr(cls: type, name: str, value: Any) -> None: value.__set_name__(cls, name) +def _route_arg_type(var: DynamicRouteVar) -> str: + """Get the route arg type a page installed a dynamic route var as. + + Args: + var: The dynamic route var. + + Returns: + ``RouteArgType.LIST`` for the catch-all, ``RouteArgType.SINGLE`` otherwise. + """ + return ( + constants.RouteArgType.LIST + if var._var_type == list[str] + else constants.RouteArgType.SINGLE + ) + + def _router_fget(self: BaseState) -> RouterData: """Assemble the RouterData view over the per-field router vars. @@ -1602,11 +1618,7 @@ def _dynamic_route_arg_types(cls) -> builtins.dict[str, str]: A mapping of dynamic route argument name to ``RouteArgType`` value. """ return { - name: ( - constants.RouteArgType.LIST - if computed_var._var_type == list[str] - else constants.RouteArgType.SINGLE - ) + name: _route_arg_type(computed_var) for name, computed_var in cls.computed_vars.items() if isinstance(computed_var, DynamicRouteVar) } @@ -1670,69 +1682,6 @@ def inner_func(self: BaseState) -> list[str]: cls.vars.update(dynamic_vars) cls._update_substate_vars(dynamic_vars) - @classmethod - def _installed_route_arg(cls, name: str, arg_type: str, kind: str) -> Any: - """Get the var a page installed for a dynamic route arg of the given type. - - Args: - name: The name of the dynamic route arg. - arg_type: The ``RouteArgType`` the arg must have. - kind: How the arg appears in a route, for the error message. - - Returns: - The var of the dynamic route arg, as class access returns it. - - Raises: - DynamicRouteArgNotFoundError: If no added page declares the arg as `kind`. - """ - var = cls.vars.get(name) - if not isinstance(var, DynamicRouteVar): - msg = f"No page added so far declares the dynamic route arg {kind}." - raise DynamicRouteArgNotFoundError(msg) - installed = ( - constants.RouteArgType.LIST - if var._var_type == list[str] - else constants.RouteArgType.SINGLE - ) - if installed != arg_type: - msg = f"The pages added so far declare `{name}`, but not as {kind}." - raise DynamicRouteArgNotFoundError(msg) - return getattr(cls, name) - - @classmethod - def route_arg(cls, name: str) -> StringVar: - """Get the var of a dynamic route arg, typed. - - Adding a page at ``/post/[pid]`` installs the var ``rx.State.pid``. Type - checkers cannot see that attribute, which only exists once the page is - added; ``rx.State.route_arg("pid")`` returns the same var as a - ``StringVar``. The ``[[...splat]]`` catch-all is ``route_catch_all()``. - - Args: - name: The name of the dynamic route arg. - - Returns: - The var of the dynamic route arg. - """ - return cls._installed_route_arg( - name, constants.RouteArgType.SINGLE, f"[{name}]" - ) - - @classmethod - def route_catch_all(cls) -> ArrayVar[list[str]]: - """Get the var of the ``[[...splat]]`` catch-all route arg, typed. - - Adding a page at ``/docs/[[...splat]]`` installs the var - ``rx.State.splat`` with the remaining path segments, which type checkers - cannot see; this returns the same var as an ``ArrayVar[list[str]]``. - - Returns: - The var of the catch-all route arg. - """ - return cls._installed_route_arg( - "splat", constants.RouteArgType.LIST, constants.RouteRegex.SPLAT_CATCHALL - ) - if TYPE_CHECKING or environment.REFLEX_ENV_MODE.get() != constants.Env.PROD: def __setattr__(self, name: str, value: Any): @@ -3092,6 +3041,81 @@ def wrapper() -> Component: return wrapper +def _installed_route_arg(name: str) -> tuple[Any, str] | None: + """Get the var a page installed on ``rx.State`` for a dynamic route arg. + + Args: + name: The name of the dynamic route arg. + + Returns: + The var as class access returns it and its ``RouteArgType``, or None if + no page added so far has the arg. + """ + var = State.vars.get(name) + if not isinstance(var, DynamicRouteVar): + return None + return getattr(State, name), _route_arg_type(var) + + +def route_arg(name: str) -> StringVar: + """Get the var of a dynamic route arg, such as ``pid`` in ``/post/[pid]``. + + Adding the page installs the var ``rx.State.pid``, which type checkers cannot + see; this returns the same var, typed. Like ``rx.State.pid``, it is a var for + building components, not the value: an event handler or a computed var reads + the value from the state as before. The ``[[...splat]]`` catch-all is + ``route_catch_all()``. + + Args: + name: The name of the dynamic route arg, as in ``[name]`` or the + optional ``[[name]]``. + + Returns: + The var of the dynamic route arg. + + Raises: + DynamicRouteArgNotFoundError: If no page added so far has the arg, or the + arg is the catch-all. + """ + installed = _installed_route_arg(name) + if installed is None: + msg = f"No dynamic route arg `{name}` is installed: no page added so far has `[{name}]` in its route." + raise DynamicRouteArgNotFoundError(msg) + var, arg_type = installed + if arg_type != constants.RouteArgType.SINGLE: + msg = f"`{name}` is installed as the catch-all `{constants.RouteRegex.SPLAT_CATCHALL}`; use `rx.route_catch_all()` for it." + raise DynamicRouteArgNotFoundError(msg) + return var + + +def route_catch_all() -> ArrayVar[list[str]]: + """Get the var of the ``[[...splat]]`` catch-all route arg. + + Adding a page at ``/docs/[[...splat]]`` installs the var ``rx.State.splat`` + with the remaining path segments, which type checkers cannot see; this + returns the same var, typed. Like ``rx.State.splat``, it is a var for building + components, not the value: an event handler or a computed var reads the value + from the state as before. + + Returns: + The var of the catch-all route arg. + + Raises: + DynamicRouteArgNotFoundError: If no page added so far has the catch-all, + or ``splat`` is a regular dynamic route arg. + """ + name = constants.RouteRegex.SPLAT_ARG + installed = _installed_route_arg(name) + if installed is None: + msg = f"No catch-all route arg is installed: no page added so far has `{constants.RouteRegex.SPLAT_CATCHALL}` in its route." + raise DynamicRouteArgNotFoundError(msg) + var, arg_type = installed + if arg_type != constants.RouteArgType.LIST: + msg = f'`{name}` is installed as the regular dynamic route arg `[{name}]`; use `rx.route_arg("{name}")` for it.' + raise DynamicRouteArgNotFoundError(msg) + return var + + # sessionStorage key holding the ms timestamp of the last reload on error LAST_RELOADED_KEY = "reflex_last_reloaded_on_error" diff --git a/tests/type_checking/state.py b/tests/type_checking/state.py index 10ed646c96a..158b74d531d 100644 --- a/tests/type_checking/state.py +++ b/tests/type_checking/state.py @@ -6,7 +6,7 @@ from reflex.vars.sequence import ArrayVar, StringVar # `rx.State.pid` only exists once a page at `/post/[pid]` is added, so type -# checkers cannot see it; `route_arg` returns the same var, typed, and -# `route_catch_all` the one of a `[[...splat]]` catch-all. -assert_type(rx.State.route_arg("pid"), StringVar) -assert_type(rx.State.route_catch_all(), ArrayVar[list[str]]) +# checkers cannot see it; `rx.route_arg` returns the same var, typed, and +# `rx.route_catch_all` the one of a `[[...splat]]` catch-all. +assert_type(rx.route_arg("pid"), StringVar) +assert_type(rx.route_catch_all(), ArrayVar[list[str]]) diff --git a/tests/units/test_app.py b/tests/units/test_app.py index 343468ba6fe..b348f5f4eac 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -46,7 +46,6 @@ from reflex_base.utils.imports import ImportVar from reflex_base.utils.types import ASGIApp, Receive, Scope, Send from reflex_base.vars.base import computed_var -from reflex_base.vars.sequence import ArrayVar, StringVar from reflex_components_core.base.bare import Bare from reflex_components_core.base.fragment import Fragment from reflex_components_core.core import _upload as upload_module @@ -376,57 +375,6 @@ def test_add_page_set_route_dynamic(index_page: ComponentCallable): assert "rx_router_page" in app._state()._var_dependencies -def test_route_arg(index_page: ComponentCallable): - """Get the vars of a page's dynamic route args through the typed accessors. - - Args: - index_page: The index page. - """ - app = App(_state=EmptyState) - assert app._state is not None - app.add_page(index_page, route="/route-arg/[dynamic]/[[...splat]]") - - # the same vars as the attributes the page added, e.g. `EmptyState.dynamic` - dynamic = app._state.route_arg("dynamic") - assert isinstance(dynamic, StringVar) - assert dynamic._js_expr == getattr(app._state, "dynamic")._js_expr # noqa: B009 - splat = app._state.route_catch_all() - assert isinstance(splat, ArrayVar) - assert splat._js_expr == getattr(app._state, "splat")._js_expr # noqa: B009 - - with pytest.raises(exceptions.DynamicRouteArgNotFoundError) as err: - app._state.route_arg("not_added") - assert str(err.value) == ( - "No page added so far declares the dynamic route arg [not_added]." - ) - with pytest.raises(exceptions.DynamicRouteArgNotFoundError) as err: - app._state.route_arg("splat") - assert ( - str(err.value) == "The pages added so far declare `splat`, but not as [splat]." - ) - - -def test_route_catch_all_of_a_regular_arg(index_page: ComponentCallable): - """A regular arg named `splat` is no catch-all. - - Args: - index_page: The index page. - """ - - class RegularSplatState(BaseState): - """State whose only page has a regular `splat` arg.""" - - app = App(_state=RegularSplatState) - app.add_page(index_page, route="/regular-splat/[splat]") - - assert isinstance(RegularSplatState.route_arg("splat"), StringVar) - with pytest.raises(exceptions.DynamicRouteArgNotFoundError) as err: - RegularSplatState.route_catch_all() - assert str(err.value) == ( - "The pages added so far declare `splat`, but not as [[...splat]]." - ) - - def test_add_page_set_route_nested(app: App, index_page: ComponentCallable): """Test adding a page to an app. diff --git a/tests/units/test_state.py b/tests/units/test_state.py index 4a516554069..8d32f09e568 100644 --- a/tests/units/test_state.py +++ b/tests/units/test_state.py @@ -41,6 +41,7 @@ from reflex_base.registry import RegistrationContext from reflex_base.utils import format, types from reflex_base.utils.exceptions import ( + DynamicRouteArgNotFoundError, EventHandlerValueError, InvalidLockWarningThresholdError, LockExpiredError, @@ -54,6 +55,7 @@ ) from reflex_base.utils.format import json_dumps from reflex_base.vars.base import Field, Var, computed_var, field +from reflex_base.vars.sequence import ArrayVar, StringVar from typing_extensions import TypeAliasType import reflex as rx @@ -74,6 +76,7 @@ from reflex.istate.manager.redis import StateManagerRedis from reflex.istate.manager.token import BaseStateToken from reflex.istate.proxy import MutableProxy, StateProxy +from reflex.route import get_route_args from reflex.state import ( BaseState, ImmutableStateError, @@ -4455,6 +4458,125 @@ def test_router_field_names_are_reserved(name): ) +@pytest.fixture +def route_arg_root(monkeypatch: pytest.MonkeyPatch) -> type[BaseState]: + """A fresh root state for `rx.route_arg` and `rx.route_catch_all` to resolve against. + + Route args installed on `rx.State` would stay for the rest of the session, + and one root cannot hold both a regular `[splat]` and the catch-all. + + Args: + monkeypatch: The pytest monkeypatch fixture. + + Returns: + The root state the accessors resolve against. + """ + + class RouteArgRoot(BaseState): + """Root state standing in for `rx.State`.""" + + monkeypatch.setattr("reflex.state.State", RouteArgRoot) + return RouteArgRoot + + +def test_route_arg(route_arg_root: type[BaseState]): + """`rx.route_arg` returns the var a page installed for a regular or optional arg. + + Args: + route_arg_root: The root state the accessors resolve against. + """ + + class RouteArgSubState(route_arg_root): + """A substate, which reads the route args of its root.""" + + route_arg_root.setup_dynamic_args(get_route_args("/post/[pid]/[[lang]]")) + + for name in ("pid", "lang"): + var = rx.route_arg(name) + assert isinstance(var, StringVar) + assert var.equals(getattr(route_arg_root, name)) + assert var.equals(getattr(RouteArgSubState, name)) + + +def test_route_catch_all(route_arg_root: type[BaseState]): + """`rx.route_catch_all` returns the var a page installed for `[[...splat]]`. + + Args: + route_arg_root: The root state the accessors resolve against. + """ + route_arg_root.setup_dynamic_args(get_route_args("/docs/[[...splat]]")) + + splat = rx.route_catch_all() + assert isinstance(splat, ArrayVar) + assert splat.equals(getattr(route_arg_root, "splat")) # noqa: B009 + + with pytest.raises(DynamicRouteArgNotFoundError) as err: + rx.route_arg("splat") + assert str(err.value) == ( + "`splat` is installed as the catch-all `[[...splat]]`; use " + "`rx.route_catch_all()` for it." + ) + + +def test_route_catch_all_of_a_regular_arg(route_arg_root: type[BaseState]): + """A regular arg named `splat` is no catch-all. + + Args: + route_arg_root: The root state the accessors resolve against. + """ + route_arg_root.setup_dynamic_args(get_route_args("/post/[splat]")) + + assert rx.route_arg("splat").equals(getattr(route_arg_root, "splat")) # noqa: B009 + with pytest.raises(DynamicRouteArgNotFoundError) as err: + rx.route_catch_all() + assert str(err.value) == ( + "`splat` is installed as the regular dynamic route arg `[splat]`; use " + '`rx.route_arg("splat")` for it.' + ) + + +def test_route_arg_not_installed(route_arg_root: type[BaseState]): + """The accessors raise for an arg no page added so far has. + + Args: + route_arg_root: The root state the accessors resolve against. + """ + with pytest.raises(DynamicRouteArgNotFoundError) as err: + rx.route_arg("pid") + assert str(err.value) == ( + "No dynamic route arg `pid` is installed: no page added so far has " + "`[pid]` in its route." + ) + with pytest.raises(DynamicRouteArgNotFoundError) as err: + rx.route_catch_all() + assert str(err.value) == ( + "No catch-all route arg is installed: no page added so far has " + "`[[...splat]]` in its route." + ) + + +def test_route_accessor_names_are_not_reserved(route_arg_root: type[BaseState]): + """A state var, event handler or route arg can be named like the accessors. + + Args: + route_arg_root: The root state the accessors resolve against. + """ + + class RouteAccessorNamesState(BaseState): + """A state declaring the names of the accessors.""" + + route_arg: str = "" + + def route_catch_all(self): + """An event handler named like `rx.route_catch_all`.""" + + assert "route_arg" in RouteAccessorNamesState.get_fields() + assert "route_catch_all" in RouteAccessorNamesState.event_handlers + + route_arg_root.setup_dynamic_args(get_route_args("/x/[route_arg]")) + assert rx.route_arg("route_arg").equals(getattr(route_arg_root, "route_arg")) # noqa: B009 + + def test_router_var_dep_legacy_string() -> None: """An explicit deps=["router"] still fires when any router var changes.