From 6203716934cd68feb7fe99696320b3d2b5dfc85b Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Sat, 21 Nov 2026 20:33:30 +0100 Subject: [PATCH 1/3] fix: accept bound methods as rx.foreach render functions --- .../+foreach-bound-method-render-fn.bugfix.md | 1 + .../reflex_base/components/tags/iter_tag.py | 5 ++- tests/units/components/core/test_foreach.py | 41 +++++++++++++++++++ 3 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 packages/reflex-base/news/+foreach-bound-method-render-fn.bugfix.md diff --git a/packages/reflex-base/news/+foreach-bound-method-render-fn.bugfix.md b/packages/reflex-base/news/+foreach-bound-method-render-fn.bugfix.md new file mode 100644 index 00000000000..90d472ef2b5 --- /dev/null +++ b/packages/reflex-base/news/+foreach-bound-method-render-fn.bugfix.md @@ -0,0 +1 @@ +`rx.foreach` accepts a bound method (a classmethod or an instance method) as its render function; its `cls`/`self` no longer counts as a render argument. diff --git a/packages/reflex-base/src/reflex_base/components/tags/iter_tag.py b/packages/reflex-base/src/reflex_base/components/tags/iter_tag.py index a91d645393d..01cdbc2df21 100644 --- a/packages/reflex-base/src/reflex_base/components/tags/iter_tag.py +++ b/packages/reflex-base/src/reflex_base/components/tags/iter_tag.py @@ -104,8 +104,9 @@ def render_component(self) -> Component: from reflex.compiler.compiler import _into_component_once - # Get the render function arguments. - args = inspect.getfullargspec(self.render_fn).args + # Get the render function arguments. Unlike getfullargspec, signature leaves + # out the cls/self of a bound method, matching Foreach's validation. + args = inspect.signature(self.render_fn).parameters arg = self.get_arg_var() index = self.get_index_var() diff --git a/tests/units/components/core/test_foreach.py b/tests/units/components/core/test_foreach.py index a1a7f92b109..84c6c3ed6d0 100644 --- a/tests/units/components/core/test_foreach.py +++ b/tests/units/components/core/test_foreach.py @@ -3,6 +3,7 @@ import pytest from reflex_base.components.component import Component from reflex_base.constants.state import FIELD_MARKER +from reflex_base.vars.base import Var from reflex_base.vars.number import NumberVar from reflex_base.vars.sequence import ArrayVar from reflex_components_core.core.foreach import ( @@ -283,6 +284,46 @@ def test_foreach_too_many_params_in_signature(): ) +class _BoundRenderFns: + """Render functions bound to a class or an instance.""" + + @classmethod + def color(cls, color: Var[str]) -> Component: + return text(color) + + @classmethod + def color_with_index(cls, color: Var[str], index: NumberVar[int]) -> Component: + return text(color, index) + + def instance_color_with_index( + self, color: Var[str], index: NumberVar[int] + ) -> Component: + return text(color, index) + + +@pytest.mark.parametrize( + ("render_fn", "renders_index"), + [ + (_BoundRenderFns.color, False), + (_BoundRenderFns.color_with_index, True), + (_BoundRenderFns().instance_color_with_index, True), + ], + ids=["classmethod", "classmethod-with-index", "method-with-index"], +) +def test_foreach_bound_method_render_fn(render_fn, renders_index: bool): + """Test that the bound cls/self does not count as a render function argument. + + Args: + render_fn: The bound render function. + renders_index: Whether the render function takes the index. + """ + component = Foreach.create(ForEachState.colors_list, render_fn) + + rendered = str(component) + assert "color_rx_state_" in rendered + assert ("index_rx_state_" in rendered) is renders_index + + def test_foreach_component_styles(): """Test that the foreach component works with global component styles.""" component = el.div( From a96668a385f626ce80b5d2b5e036047132caefd6 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Sat, 21 Nov 2026 20:44:57 +0100 Subject: [PATCH 2/3] fix: give the foreach item and index only to positional render function parameters --- .../+foreach-bound-method-render-fn.bugfix.md | 2 +- .../reflex_base/components/tags/iter_tag.py | 32 ++++- ...foreach-positional-render-params.bugfix.md | 1 + .../reflex_components_core/core/foreach.py | 5 +- tests/units/components/core/test_foreach.py | 111 ++++++++++++++++-- 5 files changed, 131 insertions(+), 20 deletions(-) create mode 100644 packages/reflex-components-core/news/+foreach-positional-render-params.bugfix.md diff --git a/packages/reflex-base/news/+foreach-bound-method-render-fn.bugfix.md b/packages/reflex-base/news/+foreach-bound-method-render-fn.bugfix.md index 90d472ef2b5..d172b3af42f 100644 --- a/packages/reflex-base/news/+foreach-bound-method-render-fn.bugfix.md +++ b/packages/reflex-base/news/+foreach-bound-method-render-fn.bugfix.md @@ -1 +1 @@ -`rx.foreach` accepts a bound method (a classmethod or an instance method) as its render function; its `cls`/`self` no longer counts as a render argument. +`rx.foreach` accepts a bound method (a classmethod or an instance method) as its render function: its `cls`/`self` no longer counts as a render argument. Only positional parameters take the item and its index; keyword-only parameters and `**kwargs` never receive the index. diff --git a/packages/reflex-base/src/reflex_base/components/tags/iter_tag.py b/packages/reflex-base/src/reflex_base/components/tags/iter_tag.py index 01cdbc2df21..f4e977240e4 100644 --- a/packages/reflex-base/src/reflex_base/components/tags/iter_tag.py +++ b/packages/reflex-base/src/reflex_base/components/tags/iter_tag.py @@ -33,6 +33,33 @@ def _loop_var_data(name: str) -> VarData: return VarData(deps=[Var(_js_expr=name)]) +_POSITIONAL_KINDS = ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, +) + + +def _render_fn_params(render_fn: Callable) -> list[inspect.Parameter]: + """Get the parameters a foreach render function takes its render arguments in. + + The render arguments are the item and its index, passed positionally to the + positional parameters. A render function without any, like ``rx.text``, whose + ``create`` takes its children as ``*children``, gets the item only. Keyword-only + parameters, ``**kwargs`` and the cls/self of a bound method don't count. + + Args: + render_fn: The render function. + + Returns: + The parameters that take the render arguments. + """ + params = inspect.signature(render_fn).parameters.values() + positional = [param for param in params if param.kind in _POSITIONAL_KINDS] + if positional: + return positional + return [param for param in params if param.kind is inspect.Parameter.VAR_POSITIONAL] + + @dataclasses.dataclass(frozen=True) class IterTag(CommonTag): """An iterator tag.""" @@ -104,9 +131,8 @@ def render_component(self) -> Component: from reflex.compiler.compiler import _into_component_once - # Get the render function arguments. Unlike getfullargspec, signature leaves - # out the cls/self of a bound method, matching Foreach's validation. - args = inspect.signature(self.render_fn).parameters + # Get the render function arguments. + args = _render_fn_params(self.render_fn) arg = self.get_arg_var() index = self.get_index_var() diff --git a/packages/reflex-components-core/news/+foreach-positional-render-params.bugfix.md b/packages/reflex-components-core/news/+foreach-positional-render-params.bugfix.md new file mode 100644 index 00000000000..81764c2427b --- /dev/null +++ b/packages/reflex-components-core/news/+foreach-positional-render-params.bugfix.md @@ -0,0 +1 @@ +`rx.foreach` validates and names its render function's parameters by the positional ones only, so a bound method, a keyword-only parameter or `**kwargs` no longer counts as the index parameter. diff --git a/packages/reflex-components-core/src/reflex_components_core/core/foreach.py b/packages/reflex-components-core/src/reflex_components_core/core/foreach.py index 0000a14c457..da8f4986955 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/foreach.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/foreach.py @@ -3,13 +3,13 @@ from __future__ import annotations import functools -import inspect from collections.abc import Callable, Iterable from hashlib import md5 from typing import Any from reflex_base.components.component import Component, field from reflex_base.components.tags import IterTag +from reflex_base.components.tags.iter_tag import _render_fn_params from reflex_base.constants import MemoizationMode from reflex_base.constants.state import FIELD_MARKER from reflex_base.utils import types @@ -143,8 +143,7 @@ def create( def _render(self) -> IterTag: props = {} - render_sig = inspect.signature(self.render_fn) - params = list(render_sig.parameters.values()) + params = _render_fn_params(self.render_fn) # Validate the render function signature. if len(params) == 0 or len(params) > 2: diff --git a/tests/units/components/core/test_foreach.py b/tests/units/components/core/test_foreach.py index 84c6c3ed6d0..ccd1487f98a 100644 --- a/tests/units/components/core/test_foreach.py +++ b/tests/units/components/core/test_foreach.py @@ -1,4 +1,7 @@ +import re +from collections.abc import Callable from dataclasses import dataclass +from typing import Any import pytest from reflex_base.components.component import Component @@ -289,39 +292,121 @@ class _BoundRenderFns: @classmethod def color(cls, color: Var[str]) -> Component: + """Render a color. + + Args: + color: The color. + + Returns: + The rendered color. + """ return text(color) @classmethod def color_with_index(cls, color: Var[str], index: NumberVar[int]) -> Component: + """Render a color with its index. + + Args: + color: The color. + index: The index of the color. + + Returns: + The rendered color. + """ return text(color, index) def instance_color_with_index( self, color: Var[str], index: NumberVar[int] ) -> Component: + """Render a color with its index. + + Args: + color: The color. + index: The index of the color. + + Returns: + The rendered color. + """ return text(color, index) + @classmethod + def color_with_keyword_only( + cls, color: Var[str], *, key: str | None = None + ) -> Component: + """Render a color with a keyword-only parameter, which takes no render argument. + + Args: + color: The color. + key: The key of the rendered color. + + Returns: + The rendered color. + """ + return text(color, key=key) + + @classmethod + def color_with_kwargs(cls, color: Var[str], **props: Any) -> Component: + """Render a color with ``**kwargs``, which take no render argument. + + Args: + color: The color. + **props: The props of the rendered color. + + Returns: + The rendered color. + """ + return text(color, **props) + @pytest.mark.parametrize( - ("render_fn", "renders_index"), + ("render_fn", "item_name", "takes_index"), [ - (_BoundRenderFns.color, False), - (_BoundRenderFns.color_with_index, True), - (_BoundRenderFns().instance_color_with_index, True), + (_BoundRenderFns.color, "color", False), + (_BoundRenderFns.color_with_index, "color", True), + (_BoundRenderFns().instance_color_with_index, "color", True), + (_BoundRenderFns.color_with_keyword_only, "color", False), + (_BoundRenderFns.color_with_kwargs, "color", False), + (text, "children", False), + ], + ids=[ + "classmethod", + "classmethod-with-index", + "method-with-index", + "keyword-only", + "kwargs", + "component-create", ], - ids=["classmethod", "classmethod-with-index", "method-with-index"], ) -def test_foreach_bound_method_render_fn(render_fn, renders_index: bool): - """Test that the bound cls/self does not count as a render function argument. +def test_foreach_render_fn_takes_only_positional_render_args( + render_fn: Callable[..., Component], item_name: str, takes_index: bool +): + """Test that only positional parameters take the item and the index. + + The cls/self of a bound method, keyword-only parameters and ``**kwargs`` don't + count as render arguments, and a component's ``create`` gets the item as its only + child. Args: - render_fn: The bound render function. - renders_index: Whether the render function takes the index. + render_fn: The render function. + item_name: The name of the parameter that takes the item. + takes_index: Whether the render function takes the index. """ component = Foreach.create(ForEachState.colors_list, render_fn) - - rendered = str(component) - assert "color_rx_state_" in rendered - assert ("index_rx_state_" in rendered) is renders_index + # without an index parameter, the index is named after a hash of the render function + rendered = re.sub(r"index_[0-9a-f]{32}", "index_", str(component)) + + item = f"{item_name}{FIELD_MARKER}" + if takes_index: + index = f"index{FIELD_MARKER}" + children = f"{item},{index}" + else: + index = "index_" + children = item + iterable = f"{ForEachState.get_full_name()}.colors_list{FIELD_MARKER}" + assert rendered == ( + f"Array.prototype.map.call({iterable} ?? [],(({item},{index})=>" + f'(jsx(RadixThemesText,{{as:"p",key:{index}}},{children}))))' + ) def test_foreach_component_styles(): From 1edc6042cc6ead9e9408a69f0d5b582ca8b4ab38 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Sat, 21 Nov 2026 21:27:49 +0100 Subject: [PATCH 3/3] build: require the reflex-base dev release with _render_fn_params in reflex-components-core --- packages/reflex-components-core/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/reflex-components-core/pyproject.toml b/packages/reflex-components-core/pyproject.toml index 16100a576f4..579a4e8baaf 100644 --- a/packages/reflex-components-core/pyproject.toml +++ b/packages/reflex-components-core/pyproject.toml @@ -16,7 +16,7 @@ classifiers = [ "Programming Language :: Python :: 3.15", ] dependencies = [ - "reflex-base >= 0.11.0", + "reflex-base >= 0.11.1.dev0", "reflex-components-lucide >= 1.1.0", "reflex-components-sonner >= 0.10.0", "python_multipart >= 0.0.21",