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

[ENG-4165] Consider default and default_factory for state vars #4510

Merged
merged 2 commits into from
Dec 12, 2024
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
1 change: 1 addition & 0 deletions reflex/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -1081,6 +1081,7 @@ def _set_default_value(cls, prop: Var):
if (
not field.required
and field.default is None
and field.default_factory is None
and not types.is_optional(prop._var_type)
):
# Ensure frontend uses null coalescing when accessing.
Expand Down
18 changes: 18 additions & 0 deletions tests/units/components/core/test_foreach.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from typing import Dict, List, Set, Tuple, Union

import pydantic.v1
import pytest

from reflex import el
from reflex.base import Base
from reflex.components.component import Component
from reflex.components.core.foreach import (
Foreach,
Expand All @@ -18,6 +20,12 @@
from reflex.vars.sequence import ArrayVar


class ForEachTag(Base):
"""A tag for testing the ForEach component."""

name: str = ""


class ForEachState(BaseState):
"""A state for testing the ForEach component."""

Expand Down Expand Up @@ -46,6 +54,8 @@ class ForEachState(BaseState):
bad_annotation_list: list = [["red", "orange"], ["yellow", "blue"]]
color_index_tuple: Tuple[int, str] = (0, "red")

default_factory_list: list[ForEachTag] = pydantic.v1.Field(default_factory=list)


class ComponentStateTest(ComponentState):
"""A test component state."""
Expand Down Expand Up @@ -290,3 +300,11 @@ def test_foreach_component_state():
ForEachState.colors_list,
ComponentStateTest.create,
)


def test_foreach_default_factory():
"""Test that the default factory is called."""
_ = Foreach.create(
ForEachState.default_factory_list,
lambda tag: text(tag.name),
)
Loading