Reject clashing mixin vars; let mixin vars without a default use the parent's

Closed
QU
2mo ago
+55-0

Summary

Tightens how state mixins declare vars, the original intent of this PR (#7190), on top of the field binding from #7312:

  • Conflicting mixins: two mixins that do not inherit from one another can no longer declare a var of the same name, with or without a default, and the same goes for backend vars. Creating the state or mixin that combines them raises the new MixinVarNameConflictError. A state is meant to combine its mixins into one coherent state, and two independent mixins sharing a var name could each use it for their own purpose. Mixins already combined into the parent state are exempt: they were checked with it, and a substate may redeclare its vars.
  • Mixin vars without a default: a var a mixin declares without a default (count: int) replaced the var of that name declared by a parent state with an independent one, defaulting to the type's zero value. It now uses the parent's var, as re-annotating it on the substate does.
  • Removed exception: BaseVarShadowsInheritedVarError, added in 0.9.12 and no longer raised since #7312, is removed.

Redeclaring an inherited var with a default, directly or through a mixin, still gives the substate an independent var, as on main.

Changes

  • reflex_base.vars.base:
    • Field._default_from_type notes a declaration without a default, and _replace keeps it while the default is carried over.
    • _declared_value looks up a var's declaration, passing over a mixin's var without a default for a parent state's var. _annotated_fields and BaseState._bind_fields use it, and _bind_fields exposes the parent's var on the class, where the mixin's would hide it.
    • BaseStateMeta runs _validate_mixin_vars, which raises MixinVarNameConflictError.
  • reflex_base.utils.exceptions: MixinVarNameConflictError replaces BaseVarShadowsInheritedVarError.
  • docs/state_structure/mixins.md: documents both rules and drops the claim that conflicting mixin vars are resolved by MRO.
  • News fragments: a breaking change and a bug fix for reflex, and a breaking change for reflex-base.

Tests

  • tests/units/test_state.py: the three mixin tests assert which declaration wins. The annotation-only test now passes, without its xfail. New cases cover a parent that got its var from a mixin of its own, and a child re-annotating the var.
  • tests/units/reflex_base/vars/test_base.py: conflicts when combining into a substate, a new root state and a mixin, for backend vars and for declarations without a default; no conflict with the parent's mixins; the Field flag.

Validation

  • uv run pytest tests/units passes, apart from browser-driver tests that need a Playwright build missing locally and fail the same way without this change.
  • Ruff, pyright, ty and the other pre-commit hooks pass. The changelog check finds fragments for reflex and reflex-base.

Refs #7190, #7312