Skip to content
Open
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 packages/reflex-base/news/+7995.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Check assignments to a state var typed with a specialized generic TypedDict (`P[str]`) against its fields, instead of crashing the event handler with an `IndexError` or logging a false type error.
44 changes: 37 additions & 7 deletions packages/reflex-base/src/reflex_base/utils/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,13 @@
_SpecialGenericAlias, # pyright: ignore [reportAttributeAccessIssue]
cast,
get_args,
is_typeddict,
)
from typing import Self as Self
from typing import get_origin as get_origin_og
from typing import get_type_hints as get_type_hints_og

import typing_extensions
from typing_extensions import TypeAliasType, TypeIs, TypeVarTuple
from typing_extensions import TypeAliasType, TypeIs, TypeVarTuple, is_typeddict
from typing_extensions import override as override

from reflex_base import constants
Expand Down Expand Up @@ -1273,6 +1272,24 @@ def get_base_class(cls: GenericType) -> type:
)


@lru_cache
def _runtime_typed_dict_field_types(cls: GenericType) -> dict[str, Any]:
"""Resolve the field types for repeated runtime TypedDict checks.

Args:
cls: The TypedDict class or specialization being checked.

Returns:
The field types used for runtime validation.
"""
if sys.version_info[:2] == (3, 11) and typing.is_typeddict(cls):
if "__orig_bases__" not in vars(cls):
# Python 3.11 can discard specialized bases of stdlib TypedDicts.
# Keep checking the available field hints when they cannot be recovered.
return get_type_hints(cls)
return get_typed_dict_field_types(cls)


def does_obj_satisfy_typed_dict(
obj: Any,
cls: GenericType,
Expand All @@ -1296,10 +1313,11 @@ def does_obj_satisfy_typed_dict(
if not isinstance(obj, Mapping):
return False

key_names_to_values = get_type_hints(cls)
required_keys: frozenset[str] = getattr(cls, "__required_keys__", frozenset())
is_closed = getattr(cls, "__closed__", False)
extra_items_type = getattr(cls, "__extra_items__", Any)
origin = get_origin_og(cls) or cls
key_names_to_values = _runtime_typed_dict_field_types(cls)
required_keys: frozenset[str] = getattr(origin, "__required_keys__", frozenset())
is_closed = getattr(origin, "__closed__", False)
extra_items_type = getattr(origin, "__extra_items__", Any)
if any(extra_items_type is sentinel for sentinel in _NO_EXTRA_ITEMS_SENTINELS):
# Extra keys of a non-closed TypedDict are unconstrained; a closed
# one already rejected them above.
Expand Down Expand Up @@ -1448,7 +1466,6 @@ def _isinstance(
origin = origin_attr if origin_attr is not None else _get_origin_cached(cls)

if origin is None:
# cls is a typed dict
if is_typeddict(cls):
if nested:
return does_obj_satisfy_typed_dict(
Expand Down Expand Up @@ -1548,6 +1565,16 @@ def _isinstance(
return False
return True
if safe_issubclass(origin, Mapping):
if origin is not dict and typing_extensions.is_typeddict(origin):
# A specialized generic TypedDict (``P[str]``) carries the
# generic's type arguments, not a Mapping's key and value types.
return does_obj_satisfy_typed_dict(
obj,
cls,
nested=nested - 1,
treat_var_as_type=treat_var_as_type,
treat_mutable_obj_as_immutable=treat_mutable_obj_as_immutable,
)
expected_class = (
dict
if origin is dict and not treat_mutable_obj_as_immutable
Expand Down Expand Up @@ -1589,6 +1616,9 @@ def _isinstance(
if typing_extensions.is_protocol(origin):
# A subscripted protocol without @runtime_checkable cannot be checked.
return True
if typing_extensions.is_typeddict(origin):
# A specialized generic TypedDict rejects isinstance checks.
return isinstance(obj, dict)
raise


Expand Down
52 changes: 52 additions & 0 deletions tests/units/reflex_base/utils/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,57 @@ def test_get_typed_dict_field_types_through_generic_bases():
assert get_typed_dict_field_types(_GenericMiddle[int])["value"] == list[int]


@pytest.mark.parametrize(
("value", "cls", "expected"),
[
({"value": ["a"], "maybe": None}, _GenericBase[list[str]], True),
({"value": "a", "maybe": None}, _GenericBase[list[str]], False),
({"value": 1, "maybe": 2}, _GenericBase[int], True),
({"value": "a", "maybe": None}, _GenericBase[int], False),
({"value": 1, "maybe": None}, _GenericBase[int] | None, True),
(None, _GenericBase[int] | None, True),
({"value": "a", "maybe": None}, _GenericBase[int] | None, False),
({"value": ["a"], "maybe": None, "flag": True}, _GenericMiddle[str], True),
({"value": "a", "maybe": None, "flag": True}, _GenericMiddle[str], False),
(
{"value": ["a"], "maybe": None, "flag": True, "name": "x"},
_Concrete,
True,
),
(
{"value": "a", "maybe": None, "flag": True, "name": "x"},
_Concrete,
False,
),
({"value": 1}, _GenericBase[int], False),
([1], _GenericBase[int], False),
],
)
def test_isinstance_specialized_generic_typed_dict(
value: Any, cls: Any, expected: bool
) -> None:
"""A specialized generic TypedDict is checked field by field, not as a Mapping."""
assert _isinstance(value, cls, nested=2, treat_var_as_type=False) is expected


@pytest.mark.parametrize(
("value", "expected"),
[
({"value": 1, "maybe": None}, True),
({"value": "a"}, True),
([1], False),
],
)
def test_isinstance_specialized_generic_typed_dict_outer_type_only(
value: Any, expected: bool
) -> None:
"""Without nesting, only the dict itself is checked, as in production."""
assert (
_isinstance(value, _GenericBase[int], nested=0, treat_var_as_type=False)
is expected
)


class _PlainSubclass(_Concrete):
pass

Expand Down Expand Up @@ -674,6 +725,7 @@ class Concrete(Base[list[str]]):
class Plain(Concrete):
pass

assert _isinstance({"value": ["a"]}, Plain, nested=2, treat_var_as_type=False)
if sys.version_info >= (3, 12):
assert get_typed_dict_field_types(Plain) == {"value": list[str]}
else:
Expand Down
42 changes: 41 additions & 1 deletion tests/units/test_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from pathlib import Path
from textwrap import dedent
from types import FunctionType, MethodType, ModuleType
from typing import Any, ClassVar, ForwardRef, Literal, TypeVar, cast
from typing import Any, ClassVar, ForwardRef, Generic, Literal, TypedDict, TypeVar, cast
from unittest.mock import AsyncMock, Mock, patch

import pytest
Expand Down Expand Up @@ -8510,3 +8510,43 @@ class MSibling(State):
(await root.get_state(AWriter)).value = "a"
await root._get_resolved_delta()
assert (await root.get_state(MSibling)).value == "a"


_ValueT = TypeVar("_ValueT")


class _GenericValue(TypedDict, Generic[_ValueT]):
value: _ValueT


async def test_assign_specialized_generic_typed_dict_var(
caplog: pytest.LogCaptureFixture,
clean_registration_context: RegistrationContext,
):
"""Assigning to a specialized generic TypedDict var is type checked field by field.

Args:
caplog: Captured log records.
clean_registration_context: An isolated state registry.
"""

class GenericTypedDictState(State):
text: _GenericValue[str] = {"value": "a"}
number: _GenericValue[int] = {"value": 1}

state = await State().get_state(GenericTypedDictState)

with caplog.at_level(logging.ERROR):
state.text = {"value": "b"}
state.number = {"value": 2}
assert state.text == {"value": "b"}
assert state.number == {"value": 2}
assert {"text", "number"} <= state.dirty_vars
assert not caplog.records

state.number = ["c"] # pyright: ignore[reportAttributeAccessIssue]
expected = (
f"Expected field '{GenericTypedDictState.__name__}.number' to receive type"
f" '{_GenericValue[int]}', but got ['c'] of type '{list}'."
)
assert [r.getMessage() for r in caplog.records] == [expected]
Loading