From 35954f749abdcfbd9d310630c6f00551dcb30c61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Brand=C3=A9ho?= Date: Wed, 5 Feb 2025 18:23:41 +0100 Subject: [PATCH] throw error if computed var has args (#4753) * throw error if computed var has args * change message --- reflex/utils/exceptions.py | 13 +++++++++++++ reflex/vars/base.py | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/reflex/utils/exceptions.py b/reflex/utils/exceptions.py index 05fbb297c..17a1e2beb 100644 --- a/reflex/utils/exceptions.py +++ b/reflex/utils/exceptions.py @@ -91,6 +91,19 @@ class UntypedComputedVarError(ReflexError, TypeError): super().__init__(f"Computed var '{var_name}' must have a type annotation.") +class ComputedVarSignatureError(ReflexError, TypeError): + """Custom TypeError for computed var signature errors.""" + + def __init__(self, var_name: str, signature: str): + """Initialize the ComputedVarSignatureError. + + Args: + var_name: The name of the var. + signature: The invalid signature. + """ + super().__init__(f"Computed var `{var_name}{signature}` cannot take arguments.") + + class MissingAnnotationError(ReflexError, TypeError): """Custom TypeError for missing annotations.""" diff --git a/reflex/vars/base.py b/reflex/vars/base.py index be4f19955..34d626f1d 100644 --- a/reflex/vars/base.py +++ b/reflex/vars/base.py @@ -48,6 +48,7 @@ from reflex.base import Base from reflex.constants.compiler import Hooks from reflex.utils import console, exceptions, imports, serializers, types from reflex.utils.exceptions import ( + ComputedVarSignatureError, UntypedComputedVarError, VarAttributeError, VarDependencyError, @@ -2602,6 +2603,7 @@ def computed_var( Raises: ValueError: If caching is disabled and an update interval is set. VarDependencyError: If user supplies dependencies without caching. + ComputedVarSignatureError: If the getter function has more than one argument. """ if cache is False and interval is not None: raise ValueError("Cannot set update interval without caching.") @@ -2610,6 +2612,10 @@ def computed_var( raise VarDependencyError("Cannot track dependencies without caching.") if fget is not None: + sign = inspect.signature(fget) + if len(sign.parameters) != 1: + raise ComputedVarSignatureError(fget.__name__, signature=str(sign)) + if inspect.iscoroutinefunction(fget): computed_var_cls = AsyncComputedVar else: