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..d172b3af42f --- /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. 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 db3ef688f7f..164ca34a2bb 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 @@ -21,6 +21,33 @@ from reflex_base.components.component import Component +_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.""" @@ -93,7 +120,7 @@ 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 + 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/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", 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 a1a7f92b109..ccd1487f98a 100644 --- a/tests/units/components/core/test_foreach.py +++ b/tests/units/components/core/test_foreach.py @@ -1,8 +1,12 @@ +import re +from collections.abc import Callable from dataclasses import dataclass +from typing import Any 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 +287,128 @@ 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: + """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", "item_name", "takes_index"), + [ + (_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", + ], +) +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 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) + # 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(): """Test that the foreach component works with global component styles.""" component = el.div(