bypass pydantic runtime validation for state init (#4256)

* bypass pydantic runtime validation for state init
closes #4235

* cleanup
This commit is contained in:
benedikt-bartscher 2024-11-04 22:05:39 +01:00 committed by GitHub
parent 702808afa6
commit b3c199870e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 11 additions and 4 deletions

View File

@ -356,7 +356,6 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
def __init__(
self,
*args,
parent_state: BaseState | None = None,
init_substates: bool = True,
_reflex_internal_init: bool = False,
@ -367,11 +366,10 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
DO NOT INSTANTIATE STATE CLASSES DIRECTLY! Use StateManager.get_state() instead.
Args:
*args: The args to pass to the Pydantic init method.
parent_state: The parent state.
init_substates: Whether to initialize the substates in this instance.
_reflex_internal_init: A flag to indicate that the state is being initialized by the framework.
**kwargs: The kwargs to pass to the Pydantic init method.
**kwargs: The kwargs to set as attributes on the state.
Raises:
ReflexRuntimeError: If the state is instantiated directly by end user.
@ -384,7 +382,9 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
"See https://reflex.dev/docs/state/ for further information."
)
kwargs["parent_state"] = parent_state
super().__init__(*args, **kwargs)
super().__init__()
for name, value in kwargs.items():
setattr(self, name, value)
# Setup the substates (for memory state manager only).
if init_substates:

View File

@ -3404,3 +3404,10 @@ def test_fallback_pickle():
state3._g = (i for i in range(10))
pk3 = state3._serialize()
assert len(pk3) == 0
def test_typed_state() -> None:
class TypedState(rx.State):
field: rx.Field[str] = rx.field("")
_ = TypedState(field="str")