Skip to content

monkeypatch.setattr / mock.patch.object of a State var default cannot be restored: TypeError at teardown and the patched default leaks into later tests #7472

Closed

Description

@masenf

Severity: MEDIUM, regression vs 0.10.0a1 and 0.9.12 (side effect of #7461). Independently confirmed on 0.10.0a2 across 15 var kinds × 7 patch mechanisms, Python 3.11–3.14.

What happens

class Svc(rx.State):
    _limit: int = 5

def test_patch(monkeypatch):
    monkeypatch.setattr(Svc, "_limit", 99)   # passes

def test_default_is_back():
    assert Svc.get_fields()["_limit"].default == 5   # FAILS: 99

Result on a2: 1 failed, 1 passed, 1 error — the teardown restore raises TypeError: A Field cannot overwrite another field. Define a computed var to read the field at runtime instead. and the patched default leaks into every later test (and into instances). a1 and 0.9.12: 2 passed. Same for mock.patch.object, pytest-mock, public vars, rx.field() vars, mixins, ComponentState; patching through a substate gives AttributeError at teardown and leaks into the declaring parent and its other substates. Patching methods (incl. AsyncMock), handlers, computed vars and ClassVars is fine. The error text ("define a computed var") is misleading for a test suite.

Why (published 0.10.0a2 reflex_base/vars/base.py)

Two independent causes: (1) BaseStateMeta.__setattr__ (~L4764-4817) mutates the single shared Field in place, so the snapshot monkeypatch/mock take from cls.__dict__ is the mutated object; (2) _accepts_default (~L4676-4701) rejects re-assigning a Field (~L4695-4700) or Var (~L4689-4694), and the class read of a public var is its Var. There is no BaseStateMeta.__delattr__. Relaxing only (2) leaves the default silently polluted. Re-assigning the original value restores cleanly in 14/15 kinds (not for _v: int = None, where only patching State.get_fields()[name].default works). #7461's review chose to reject Var/Field assignment; the interaction with the standard patch/restore protocol is the unconsidered part.

Suggested fix

Accept the class's own Field/Var object as a restore (copy the previous default back) and stop mutating the shared Field in place when a new default is assigned (replace it or snapshot the previous default), plus a __delattr__ that restores the declared default. Keep the documented #7461 behaviour otherwise.

Repro and evidence

Activity

  1. self-assigned this
    on Oct 7, 2026
  2. added theissue type on Oct 7, 2026
  3. linear-code commented on Oct 7, 2026

    @linear-code
  4. added a commit that references this issue on Oct 8, 2026
    62d454f
  5. added
    release-train
    on Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

release-train

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions