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
15 changes: 15 additions & 0 deletions docs/state_structure/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,21 @@ This pattern is useful when you have multiple states that need to interact with

If the var is not retrievable, `get_var_value` will raise an `UnretrievableVarValueError`.

The var can also read into a state var by attribute access, item access or indexing. A key that is itself a var is resolved first, and as on the frontend, a missing key or a `None` on the way reads as `None`:

```python
first_tag = await self.get_var_value(OtherState.user.tags[0])
selected = await self.get_var_value(OtherState.rows[OtherState.selected_index])
```

`set_var_value` is the counterpart: it sets the value such a var reads. A nested value is set through the state var holding it, which marks that var dirty so the change reaches the frontend. In a background task, call it inside `async with self`, like any other state change.

```python
await self.set_var_value(OtherState.user.tags[0], "featured")
```

A var that cannot be set, such as a computed var or an operation like `OtherState.a + OtherState.b`, raises an `UnsettableVarValueError`.

## Performance Implications

When an event handler is called, Reflex will load the data not only for the substate containing
Expand Down
1 change: 1 addition & 0 deletions news/+set-var-value.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`get_var_value` resolves vars that read into a state var by attribute access, item access or indexing, such as `State.user.tags[0]` or `State.rows[State.index]`, and the new `set_var_value` sets the value such a var reads, marking the state var dirty.
1 change: 1 addition & 0 deletions packages/reflex-base/news/+var-access-path.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Indexing an array var builds an `ArrayItemOperation` instead of an anonymous var operation, and `reflex_base.vars.object.var_access_path` splits a var such as `State.user.tags[0]` into the var it reads from and the keys it reads on the way.
4 changes: 4 additions & 0 deletions packages/reflex-base/src/reflex_base/utils/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,10 @@ class UnretrievableVarValueError(ReflexError):
"""Raised when the value of a var is not retrievable."""


class UnsettableVarValueError(ReflexError):
"""Raised when the value of a var cannot be set."""


class HybridPropertyError(ReflexError):
"""Raised when a hybrid property is misused while building its frontend var."""

Expand Down
35 changes: 34 additions & 1 deletion packages/reflex-base/src/reflex_base/vars/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from .base import (
CachedVarOperation,
LiteralVar,
ToOperation,
Var,
VarData,
cached_property_no_lock,
Expand All @@ -39,7 +40,7 @@
)
from .hybrid_property import HybridProperty
from .number import BooleanVar, NumberVar, raise_unsupported_operand_types
from .sequence import ArrayVar, LiteralArrayVar, StringVar
from .sequence import ArrayItemOperation, ArrayVar, LiteralArrayVar, StringVar

OBJECT_TYPE = TypeVar("OBJECT_TYPE", covariant=True)

Expand Down Expand Up @@ -693,6 +694,38 @@ def create(
)


def var_access_path(var: Var) -> tuple[Var, tuple[Any, ...]]:
"""Split a var into the var it reads from and the keys it reads on the way.

Attribute access, item access and array indexing are followed through any
casts; every other var ends the walk. ``State.user.tags[0]`` splits into
the var of the ``user`` field and ``("tags", 0)``, while a var that reads no
key, such as ``State.a + State.b``, is its own root with no keys.

Args:
var: The var to split.

Returns:
The var it reads from, and the keys it reads in order: a literal key as
its Python value, any other key as its var.
"""
keys: list[Var] = []
while True:
if isinstance(var, ToOperation):
var = var._original
elif isinstance(var, ObjectItemOperation):
keys.append(var._key)
var = var._object
elif isinstance(var, ArrayItemOperation):
keys.append(var._index)
var = var._array
else:
break
return var, tuple(
key._var_value if isinstance(key, LiteralVar) else key for key in reversed(keys)
)


@var_operation
def object_has_own_property_operation(object: ObjectVar, key: Var):
"""Check if an object has a key.
Expand Down
75 changes: 53 additions & 22 deletions packages/reflex-base/src/reflex_base/vars/sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def __getitem__(self, i: Any) -> ArrayVar[ARRAY_VAR_TYPE] | Var:
isinstance(i, NumberVar) and i._is_strict_float()
):
raise_unsupported_operand_types("[]", (type(self), type(i)))
return array_item_operation(self, i)
return ArrayItemOperation.create(self, i).guess_type()

def length(self) -> NumberVar[int]:
"""Get the length of the array.
Expand Down Expand Up @@ -2125,31 +2125,62 @@ def _determine_value_of_array_index(
return Any


@var_operation
def array_item_operation(array: ArrayVar, index: NumberVar | int):
"""Get an item from an array.

Args:
array: The array.
index: The index of the item.
@dataclasses.dataclass(
eq=False,
frozen=True,
slots=True,
)
class ArrayItemOperation(CachedVarOperation, Var):
"""Operation to get an item from an array."""

Returns:
The item from the array.
"""
element_type = _determine_value_of_array_index(
array._var_type,
(
index
if isinstance(index, int)
else (index._var_value if isinstance(index, LiteralNumberVar) else None)
),
_array: ArrayVar = dataclasses.field(
default_factory=lambda: LiteralArrayVar.create([])
)

return var_operation_return(
js_expression=f"{array!s}?.at?.({index!s})",
var_type=element_type,
_index: NumberVar = dataclasses.field(
default_factory=lambda: LiteralNumberVar.create(0)
)

@cached_property_no_lock
def _cached_var_name(self) -> str:
"""The name of the operation.

Returns:
The name of the operation.
"""
return f"{self._array!s}?.at?.({self._index!s})"

@classmethod
def create(
cls,
array: ArrayVar,
index: NumberVar | int,
_var_data: VarData | None = None,
) -> ArrayItemOperation:
"""Create the array item operation.

Args:
array: The array to get the item from.
index: The index of the item.
_var_data: Additional hooks and imports associated with the operation.

Returns:
The array item operation.
"""
# LiteralVar.create renders a bool index as `true`, not Python's `True`.
index_var = index if isinstance(index, Var) else LiteralVar.create(index)
return cls(
_js_expr="",
_var_type=_determine_value_of_array_index(
array._var_type,
index_var._var_value
if isinstance(index_var, LiteralNumberVar)
else None,
),
_var_data=_var_data,
_array=array,
_index=index_var,
)


@var_operation
def array_range_operation(
Expand Down
4 changes: 2 additions & 2 deletions reflex/istate/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -1205,15 +1205,15 @@ def __delattr__(self, name: str):
"""
self._mark_dirty(super().__delattr__, args=(name,))

def __delitem__(self, key: str):
def __delitem__(self, key: Any):
"""Delete the item on the proxied object and mark state dirty.

Args:
key: The key of the item.
"""
self._mark_dirty(super().__delitem__, args=(key,)) # pyright: ignore[reportAttributeAccessIssue]

def __setitem__(self, key: str, value: Any):
def __setitem__(self, key: Any, value: Any):
"""Set the item on the proxied object and mark state dirty.

Args:
Expand Down
Loading
Loading