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

Prevent Substate class shadowing #1827

Merged
merged 1 commit into from
Sep 19, 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
11 changes: 10 additions & 1 deletion reflex/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ def __init__(self, *args, parent_state: State | None = None, **kwargs):
*args: The args to pass to the Pydantic init method.
parent_state: The parent state.
**kwargs: The kwargs to pass to the Pydantic init method.

Raises:
ValueError: If a substate class shadows another.
"""
kwargs["parent_state"] = parent_state
super().__init__(*args, **kwargs)
Expand All @@ -103,7 +106,13 @@ def __init__(self, *args, parent_state: State | None = None, **kwargs):

# Setup the substates.
for substate in self.get_substates():
self.substates[substate.get_name()] = substate(parent_state=self)
substate_name = substate.get_name()
if substate_name in self.substates:
raise ValueError(
f"The substate class '{substate_name}' has been defined multiple times. Shadowing "
f"substate classes is not allowed."
)
self.substates[substate_name] = substate(parent_state=self)
# Convert the event handlers to functions.
self._init_event_handlers()

Expand Down
20 changes: 20 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,3 +584,23 @@ def reassign_mutables(self):
self.test_set = {1, 2, 3, 4, "five"}

return MutableTestState()


@pytest.fixture
def duplicate_substate():
"""Create a Test state that has duplicate child substates.

Returns:
The test state.
"""

class TestState(rx.State):
pass

class ChildTestState(TestState): # type: ignore # noqa
pass

class ChildTestState(TestState): # type: ignore # noqa
pass

return TestState
5 changes: 5 additions & 0 deletions tests/test_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -1583,3 +1583,8 @@ def assert_custom_dirty():
assert_custom_dirty()
mutable_state._be_custom.custom.bar = "baz"
assert_custom_dirty()


def test_duplicate_substate_class(duplicate_substate):
with pytest.raises(ValueError):
duplicate_substate()