Skip to content

feat: get_var_value and set_var_value for vars reading into a state var - #7954

Open
benedikt-bartscher wants to merge 8 commits into
reflex-dev:mainfrom
benedikt-bartscher:var-access-path
Open

benedikt-bartscher wants to merge 8 commits into
reflex-dev:mainfrom
benedikt-bartscher:var-access-path

Conversation

@benedikt-bartscher

@benedikt-bartscher benedikt-bartscher commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

get_var_value only resolves a var that is a state field or computed var. A var that reads into one raises UnretrievableVarValueError, even though the backend holds everything needed to resolve it:

await self.get_var_value(State.user.tags[0])          # raises
await self.get_var_value(State.rows[State.selected])  # raises

There is also no way to go the other direction and set the value such a var points at. Code that receives a var for a nested value has to take the var apart itself to find the field and the attribute names, as an admin/form library does when a form field is bound to State.instance.address.city. That means reading private var internals: ObjectItemOperation._object/._key, ToOperation._original, and for array indexing the _args of an anonymous CustomVarOperation, found by matching the name of the first parameter of array_item_operation.

This PR adds the pieces for that:

  • ArrayItemOperation: indexing an ArrayVar builds a dataclass operation with _array and _index, the counterpart of ObjectItemOperation, instead of going through @var_operation. The rendered JS (array?.at?.(index)), the item type and the var data are the same. Building it skips the var_operation wrapper and is about 40% faster (3.85 → 2.19 µs per index on my machine), which matters because indexing is the hot operation in a foreach body.
  • reflex_base.vars.object.var_access_path(var) splits a var into the var it reads from and the keys it reads on the way: State.user.tags[0] → (the user field var, ("tags", 0)). It follows attribute access, item access and array indexing through any casts. A literal key comes back as its Python value, any other key as its var. Any other operation ends the walk, so State.a + State.b is its own root with no keys.
  • get_var_value resolves such vars: it resolves the root as before (from its own var data, so get_var_value silently returns wrong values for Var operations (composite / indexed / derived vars) #6629 stays fixed), then reads each key the way optional chaining does on the frontend. A missing key or a None on the way reads as None. An index reads the item Array.prototype.at reads, so a fractional one is truncated toward zero. A set reads in the order the frontend gets it: sorted where it can be in a literal, which renders it that way, and in its own order in state, which serializes it that way. A key that is itself a var is resolved first, so State.rows[State.selected] works, also across states. A literal root resolves without any state, and a var a literal holds resolves to its value.
  • set_var_value(var, value) is the counterpart. A nested value is set through the field's MutableProxy, which marks the field dirty, so the change reaches the frontend like any other mutation in a handler. It raises a new UnsettableVarValueError for a computed var, a var not associated with any state (like State.a + State.b), when the object to set the value on is None, when it is not tracked for changes (an object inside a tuple, which no MutableProxy wraps), for an index past either end, and for item assignment on a set. These are all checked before the write, because MutableProxy marks the field dirty before it assigns.
first_tag = await self.get_var_value(OtherState.user.tags[0])
await self.set_var_value(OtherState.user.tags[0], "featured")

Behavior change: get_var_value(State.items[0]) and get_var_value(State.mapping["a"]) used to raise UnretrievableVarValueError (the #6629 regression test pinned that). Now they return the value they read. Arithmetic and other operations still raise. array_item_operation is gone from reflex_base.vars.sequence: it was an undocumented module-level helper, and ArrayVar.__getitem__ was its only caller.

Open question: is set_var_value welcome as public API? The other three pieces work without it, but an admin or form library is the main user of var_access_path, and without set_var_value each such library has to reimplement walking the path and writing through the proxy.

Performance: tests/benchmarks/test_var_value.py benchmarks get_var_value and set_var_value on a plain field, an attribute read through an array item, a read whose index is a var, and the matching writes (1,000 per measured call). Uninstrumented on my machine: a plain field read takes 1.42 µs, down from 1.66 µs before this PR, a nested read 7.5 µs, a read with a var index 8.9 µs, a nested write 7.1 µs. About 40% of a nested read is MutableProxy wrapping each object on the way. I kept that: a nested read hands back the same tracked object as self.user.tags in a handler, and the write needs the proxy to mark the field dirty and to enforce the lock in background tasks. Literal keys are not awaited, and _read_key tests the class a proxy wraps, so it skips the failed check of the proxy's own type that isinstance makes first.

reflex now requires reflex-base >= 0.11.1.dev0, following "Sibling dependency floors". MutableProxy.__setitem__ and __delitem__ now take key: Any, as __getitem__ already did: they were annotated str, which a list index is not.

Docs: the get_var_value section in docs/state_structure/overview.md now covers nested vars and set_var_value. News fragments for reflex and reflex-base.

Tests: var_access_path in tests/units/reflex_base/vars/test_object.py (attribute, item and index access through casts, keys that are vars, other operations as roots), index rendering for int, bool and var indexes in test_sequence.py, nested reads in test_get_var_value_reads_into_fields (attributes, int and str keys, negative indexes, var keys, a literal root and the vars it holds, missing keys, another state), test_set_var_value / test_set_var_value_rejects_what_it_cannot_set (root and nested writes with the exact dirty vars, another state, each error with its full message), all against the in-process, disk and redis state managers, test_var_value_through_tuples_and_sets (including literal versus state set order) and test_var_value_indexes_like_array_at (fractional, negative, NaN and infinite indexes, and a write past the end that leaves nothing dirty). ArrayItemOperation is registered in test_get_leaf_vars_sorts_every_cached_operation. The unit suite passes; ruff and pyright are clean.

🤖 Generated with Claude Code

@greptile-apps

greptile-apps Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The PR changes how state handlers read and update state values.

Fix literal object key lookup and decimal array indexes before merging.

Findings

  1. P1 Literal object reads miss values ▶
  2. P1 Decimal indexes miss array items ▶

Summary

Adds nested reads through get_var_value, nested writes through set_var_value, and var_access_path.

  • State handlers can read values through nested state vars.
  • State handlers can set values through nested state vars.

Reviews (4) · Last reviewed commit: "Merge branch 'main' into var-access-path" · Reviewed by Greptile

Comment thread reflex/state.py Resolved
Comment thread reflex/state.py Resolved
Comment thread reflex/state.py Resolved
Comment thread reflex/state.py Resolved
@codspeed

codspeed Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 29.76%

3 warnings

⚠️ 22 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚠️ 2 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

⚠️ 2 benchmarks with a significant change ran in a different software environment

Their base and head results were measured with a different OS or toolchain, such as compiler, runtime or library versions, so the changes might come from this difference rather than from the code. Open an affected benchmark to see what changed.

See affected benchmarks

⚡ 2 improved benchmarks
✅ 144 untouched benchmarks
🆕 5 new benchmarks
⏩ 8 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_array_index_operation 18 ms 11.3 ms +59.22%
⚡ test_iteration_operations 12.5 ms 11.8 ms +5.76%
🆕 test_var_value[get_field] N/A 46.5 ms N/A
🆕 test_var_value[get_nested] N/A 207 ms N/A
🆕 test_var_value[get_var_key] N/A 254.5 ms N/A
🆕 test_var_value[set_field] N/A 38.5 ms N/A
🆕 test_var_value[set_nested] N/A 200.8 ms N/A

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing benedikt-bartscher:var-access-path (571530f) with main (df7f157)

Open in CodSpeed

Footnotes

  1. 8 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

Comment thread reflex/state.py Resolved
@benedikt-bartscher
benedikt-bartscher marked this pull request as ready for review November 21, 2026 13:26
@benedikt-bartscher
benedikt-bartscher requested review from a team and Alek99 as code owners November 21, 2026 13:26

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 14 files

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

Comment thread reflex/state.py Resolved
Comment thread reflex/state.py Resolved
Comment thread reflex/state.py
Comment on lines +475 to +476
if issubclass(cls, Mapping):
return value.get(key)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Literal object reads miss values

get_var_value cannot read a literal object whose key is a state var. With State.key == "a", rx.Var.create({State.key: "value"})["a"] displays "value" in the browser, but this code returns None. The literal keeps the Var as its Python dictionary key, so value.get("a") cannot find it. Resolve literal object keys before looking up the requested value.

Comment thread reflex/state.py
Comment on lines +446 to +452
if isinstance(key, int):
return key
if isinstance(key, float):
if math.isnan(key):
return 0
return int(key) if math.isfinite(key) else None
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Decimal indexes miss array items

_array_index rejects Decimal indexes, although NumberVar supports them and ArrayVar.__getitem__ accepts them. With a Decimal state field holding 1, get_var_value(State.items[State.index]) returns None, while the browser reads the second item. The matching write also raises instead of updating that item. Convert supported Decimal values to the same index the browser uses.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant