Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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()

Expand Down
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion packages/reflex-components-core/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
from reflex_base.constants import MemoizationMode
from reflex_base.constants.state import FIELD_MARKER
from reflex_base.utils import types
Expand Down Expand Up @@ -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:
Expand Down
126 changes: 126 additions & 0 deletions tests/units/components/core/test_foreach.py
Original file line number Diff line number Diff line change
@@ -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 (
Expand Down Expand Up @@ -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)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

@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_<hash>", str(component))

item = f"{item_name}{FIELD_MARKER}"
if takes_index:
index = f"index{FIELD_MARKER}"
children = f"{item},{index}"
else:
index = "index_<hash>"
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(
Expand Down
Loading