Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

state: get_value unwraps MutableProxy first #1887

Merged
merged 3 commits into from
Oct 1, 2023
Merged
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 reflex/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -1008,6 +1008,21 @@ def _clean(self):
self.dirty_vars = set()
self.dirty_substates = set()

def get_value(self, key: str) -> Any:
"""Get the value of a field (without proxying).

The returned value will NOT track dirty state updates.

Args:
key: The key of the field.

Returns:
The value of the field.
"""
if isinstance(key, MutableProxy):
return super().get_value(key.__wrapped__)
return super().get_value(key)

def dict(self, include_computed: bool = True, **kwargs) -> dict[str, Any]:
"""Convert the object to a dictionary.

Expand Down
19 changes: 19 additions & 0 deletions tests/test_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
StateUpdate,
)
from reflex.utils import prerequisites
from reflex.utils.format import json_dumps
from reflex.vars import BaseVar, ComputedVar

from .states import GenState
Expand Down Expand Up @@ -2091,6 +2092,24 @@ def test_duplicate_substate_class(duplicate_substate):
duplicate_substate()


class Foo(Base):
"""A class containing a list of str."""

tags: List[str] = ["123", "456"]


def test_json_dumps_with_mutables():
"""Test that json.dumps works with Base vars inside mutable types."""

class MutableContainsBase(State):
items: List[Foo] = [Foo()]

dict_val = MutableContainsBase().dict()
assert isinstance(dict_val["items"][0], dict)
val = json_dumps(dict_val)
assert val == '{"is_hydrated": false, "items": [{"tags": ["123", "456"]}]}'


def test_reset_with_mutables():
"""Calling reset should always reset fields to a copy of the defaults."""
default = [[0, 0], [0, 1], [1, 1]]
Expand Down
Loading