Skip to content

Commit

Permalink
remove format_state and override behavior for bare
Browse files Browse the repository at this point in the history
  • Loading branch information
adhami3310 committed Sep 23, 2024
1 parent ee3b0e6 commit 092a08a
Show file tree
Hide file tree
Showing 8 changed files with 12 additions and 56 deletions.
2 changes: 1 addition & 1 deletion reflex/compiler/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def compile_state(state: Type[BaseState]) -> dict:
initial_state = state(_reflex_internal_init=True).dict(
initial=True, include_computed=False
)
return format.format_state(initial_state)
return initial_state


def _compile_client_storage_field(
Expand Down
4 changes: 3 additions & 1 deletion reflex/components/base/bare.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from reflex.components.component import Component
from reflex.components.tags import Tag
from reflex.components.tags.tagless import Tagless
from reflex.vars.base import Var
from reflex.vars import ArrayVar, BooleanVar, ObjectVar, Var


class Bare(Component):
Expand All @@ -33,6 +33,8 @@ def create(cls, contents: Any) -> Component:

def _render(self) -> Tag:
if isinstance(self.contents, Var):
if isinstance(self.contents, (BooleanVar, ObjectVar, ArrayVar)):
return Tagless(contents=f"{{{str(self.contents.to_string())}}}")
return Tagless(contents=f"{{{str(self.contents)}}}")
return Tagless(contents=str(self.contents))

Expand Down
3 changes: 1 addition & 2 deletions reflex/middleware/hydrate_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from reflex.event import Event, get_hydrate_event
from reflex.middleware.middleware import Middleware
from reflex.state import BaseState, StateUpdate
from reflex.utils import format

if TYPE_CHECKING:
from reflex.app import App
Expand Down Expand Up @@ -43,7 +42,7 @@ async def preprocess(
setattr(state, constants.CompileVars.IS_HYDRATED, False)

# Get the initial state.
delta = format.format_state(state.dict())
delta = state.dict()
# since a full dict was captured, clean any dirtiness
state._clean()

Expand Down
3 changes: 0 additions & 3 deletions reflex/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -1790,9 +1790,6 @@ def get_delta(self) -> Delta:
for substate in self.dirty_substates.union(self._always_dirty_substates):
delta.update(substates[substate].get_delta())

# Format the delta.
delta = format.format_state(delta)

# Return the delta.
return delta

Expand Down
44 changes: 1 addition & 43 deletions reflex/utils/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union

from reflex import constants
from reflex.utils import exceptions, types
from reflex.utils import exceptions
from reflex.utils.console import deprecate

if TYPE_CHECKING:
Expand Down Expand Up @@ -624,48 +624,6 @@ def format_query_params(router_data: dict[str, Any]) -> dict[str, str]:
return {k.replace("-", "_"): v for k, v in params.items()}


def format_state(value: Any, key: Optional[str] = None) -> Any:
"""Recursively format values in the given state.
Args:
value: The state to format.
key: The key associated with the value (optional).
Returns:
The formatted state.
Raises:
TypeError: If the given value is not a valid state.
"""
from reflex.utils import serializers

# Handle dicts.
if isinstance(value, dict):
return {k: format_state(v, k) for k, v in value.items()}

# Handle lists, sets, typles.
if isinstance(value, types.StateIterBases):
return [format_state(v) for v in value]

# Return state vars as is.
if isinstance(value, types.StateBases):
return value

# Serialize the value.
serialized = serializers.serialize(value)
if serialized is not None:
return serialized

if key is None:
raise TypeError(
f"No JSON serializer found for var {value} of type {type(value)}."
)
else:
raise TypeError(
f"No JSON serializer found for State Var '{key}' of value {value} of type {type(value)}."
)


def format_state_name(state_name: str) -> str:
"""Format a state name, replacing dots with double underscore.
Expand Down
6 changes: 3 additions & 3 deletions reflex/utils/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ def serialize_base(value: Base) -> dict:
Returns:
The serialized Base.
"""
return {k: serialize(v) for k, v in value.dict().items() if not callable(v)}
return {k: v for k, v in value.dict().items() if not callable(v)}


@serializer
Expand All @@ -263,7 +263,7 @@ def serialize_list(value: Union[List, Tuple, Set]) -> list:
Returns:
The serialized list.
"""
return [serialize(item) for item in value]
return [item for item in value]


@serializer
Expand All @@ -276,7 +276,7 @@ def serialize_dict(prop: Dict[str, Any]) -> dict:
Returns:
The serialized dictionary.
"""
return {k: serialize(v) for k, v in prop.items()}
return {k: v for k, v in prop.items()}


@serializer(to=str)
Expand Down
3 changes: 1 addition & 2 deletions tests/test_app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import dataclasses
import functools
import io
import json
Expand Down Expand Up @@ -1053,7 +1052,7 @@ def _dynamic_state_event(name, val, **kwargs):
f"comp_{arg_name}": exp_val,
constants.CompileVars.IS_HYDRATED: False,
# "side_effect_counter": exp_index,
"router": dataclasses.asdict(exp_router),
"router": exp_router,
}
},
events=[
Expand Down
3 changes: 2 additions & 1 deletion tests/utils/test_format.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import datetime
import json
from typing import Any, List

import plotly.graph_objects as go
Expand Down Expand Up @@ -621,7 +622,7 @@ def test_format_state(input, output):
input: The state to format.
output: The expected formatted state.
"""
assert format.format_state(input) == output
assert json.loads(format.json_dumps(input)) == json.loads(format.json_dumps(output))


@pytest.mark.parametrize(
Expand Down

0 comments on commit 092a08a

Please sign in to comment.