From cbad41c5745a62523510687ed7c5f44bac45e79a Mon Sep 17 00:00:00 2001 From: Lendemor Date: Fri, 17 Jan 2025 14:15:07 +0100 Subject: [PATCH] check for dict passed as children for component --- reflex/components/component.py | 15 +++++++-------- reflex/utils/exceptions.py | 18 +++++++++++++++++- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/reflex/components/component.py b/reflex/components/component.py index 8649b593d..cfe9a8dc2 100644 --- a/reflex/components/component.py +++ b/reflex/components/component.py @@ -740,22 +740,21 @@ class Component(BaseComponent, ABC): # Import here to avoid circular imports. from reflex.components.base.bare import Bare from reflex.components.base.fragment import Fragment - from reflex.utils.exceptions import ComponentTypeError + from reflex.utils.exceptions import ChildrenTypeError # Filter out None props props = {key: value for key, value in props.items() if value is not None} def validate_children(children): for child in children: - if isinstance(child, tuple): + if isinstance(child, (tuple, list)): validate_children(child) + # Make sure the child is a valid type. - if not types._isinstance(child, ComponentChild): - raise ComponentTypeError( - "Children of Reflex components must be other components, " - "state vars, or primitive Python types. " - f"Got child {child} of type {type(child)}.", - ) + if isinstance(child, dict) or not types._isinstance( + child, ComponentChild + ): + raise ChildrenTypeError(component=cls.__name__, child=child) # Validate all the children. validate_children(children) diff --git a/reflex/utils/exceptions.py b/reflex/utils/exceptions.py index 339abcda1..838d0a89d 100644 --- a/reflex/utils/exceptions.py +++ b/reflex/utils/exceptions.py @@ -1,6 +1,6 @@ """Custom Exceptions.""" -from typing import NoReturn +from typing import Any, NoReturn class ReflexError(Exception): @@ -31,6 +31,22 @@ class ComponentTypeError(ReflexError, TypeError): """Custom TypeError for component related errors.""" +class ChildrenTypeError(ComponentTypeError): + """Raised when the children prop of a component is not a valid type.""" + + def __init__(self, component: str, child: Any): + """Initialize the exception. + + Args: + component: The name of the component. + child: The child that caused the error. + """ + super().__init__( + f"Component {component} received child {child} of type {type(child)}. " + "Accepted types are other components, state vars, or primitive Python types (dict excluded)." + ) + + class EventHandlerTypeError(ReflexError, TypeError): """Custom TypeError for event handler related errors."""