Skip to content

Commit

Permalink
Added inherited backend vars (#616)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucashofer committed Feb 28, 2023
1 parent 55ac6e4 commit f06de52
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions pynecone/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ class State(Base, ABC):
# Backend vars that are never sent to the client.
backend_vars: ClassVar[Dict[str, Any]] = {}

# Backend vars inherited
inherited_backend_vars: ClassVar[Dict[str, Any]] = {}

# The parent state.
parent_state: Optional[State] = None

Expand Down Expand Up @@ -130,13 +133,17 @@ def __init_subclass__(cls, **kwargs):
parent_state = cls.get_parent_state()
if parent_state is not None:
cls.inherited_vars = parent_state.vars
cls.inherited_backend_vars = parent_state.backend_vars

cls.backend_vars = {
cls.new_backend_vars = {
name: value
for name, value in cls.__dict__.items()
if utils.is_backend_variable(name)
and name not in cls.inherited_backend_vars
}

cls.backend_vars = {**cls.inherited_backend_vars, **cls.new_backend_vars}

# Set the base and computed vars.
skip_vars = set(cls.inherited_vars) | {
"parent_state",
Expand Down Expand Up @@ -450,8 +457,11 @@ def __getattribute__(self, name: str) -> Any:
Returns:
The value of the var.
"""
# Get the var from the parent state.
if name in super().__getattribute__("inherited_vars"):
inherited_vars = {
**super().__getattribute__("inherited_vars"),
**super().__getattribute__("inherited_backend_vars"),
}
if name in inherited_vars:
return getattr(super().__getattribute__("parent_state"), name)
elif name in super().__getattribute__("backend_vars"):
return super().__getattribute__("backend_vars").__getitem__(name)
Expand All @@ -467,7 +477,8 @@ def __setattr__(self, name: str, value: Any):
value: The value of the attribute.
"""
# Set the var on the parent state.
if name in self.inherited_vars:
inherited_vars = {**self.inherited_vars, **self.inherited_backend_vars}
if name in inherited_vars:
setattr(self.parent_state, name, value)
return

Expand Down

0 comments on commit f06de52

Please sign in to comment.