diff --git a/packages/reflex-base/news/+7995-generic-typeddict-assignment.bugfix.md b/packages/reflex-base/news/+7995-generic-typeddict-assignment.bugfix.md new file mode 100644 index 00000000000..6ecbe2338c0 --- /dev/null +++ b/packages/reflex-base/news/+7995-generic-typeddict-assignment.bugfix.md @@ -0,0 +1 @@ +Fix assignments to generic ``TypedDict`` state fields in production and validate specialized field types in development. diff --git a/packages/reflex-base/src/reflex_base/utils/types.py b/packages/reflex-base/src/reflex_base/utils/types.py index e05e8876d24..e7ad2abc3ef 100644 --- a/packages/reflex-base/src/reflex_base/utils/types.py +++ b/packages/reflex-base/src/reflex_base/utils/types.py @@ -34,11 +34,11 @@ _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 +from typing import is_typeddict as is_typeddict import typing_extensions from typing_extensions import TypeAliasType, TypeIs, TypeVarTuple @@ -488,6 +488,22 @@ def get_typed_dict_field_types(typed_dict: Any) -> dict[str, Any]: declare, as when Python 3.11 drops the type arguments of a ``typing.TypedDict`` subclass of a specialized generic TypedDict. """ + return _get_typed_dict_field_types(typed_dict, allow_undeclared=False) + + +def _get_typed_dict_field_types( + typed_dict: Any, *, allow_undeclared: bool +) -> dict[str, Any]: + """Resolve fields for schema introspection or runtime validation. + + Args: + typed_dict: The TypedDict class or specialization. + allow_undeclared: Keep unresolved type variables for runtime checks + when an older Python version has dropped inherited type arguments. + + Returns: + The resolved hints, possibly containing unresolved type variables. + """ origin = get_origin_og(typed_dict) or typed_dict field_types = _typed_dict_hints(origin, include_extras=False) # Hints of inherited fields still name the generic base's type parameters, @@ -512,7 +528,9 @@ def get_typed_dict_field_types(typed_dict: Any) -> dict[str, Any]: base_annotations = _typed_dict_annotations(base_origin) field_types.update( (name, hint) - for name, hint in get_typed_dict_field_types(base).items() + for name, hint in _get_typed_dict_field_types( + base, allow_undeclared=allow_undeclared + ).items() if annotations[name] == base_annotations[name] ) substitution = _match_type_args( @@ -520,11 +538,10 @@ def get_typed_dict_field_types(typed_dict: Any) -> dict[str, Any]: ) declared = getattr(typed_dict, "__parameters__", ()) for name, hint in field_types.items(): - if isinstance(hint, TypeVar) and hint in substitution: - hint = substitution[hint] - elif substitution and (params := getattr(hint, "__parameters__", ())): - hint = _apply_type_params(hint, params, substitution) - hint = resolve_type_alias(hint) + hint = _specialize_typed_dict_hint(hint, substitution) + field_types[name] = hint + if allow_undeclared: + continue params = ( (hint,) if isinstance(hint, TypeVar) @@ -539,10 +556,26 @@ def get_typed_dict_field_types(typed_dict: Any) -> dict[str, Any]: "typing_extensions.TypedDict instead." ) raise TypeError(msg) - field_types[name] = hint return field_types +def _specialize_typed_dict_hint(hint: Any, substitution: dict[Any, Any]) -> Any: + """Apply a TypedDict specialization to a field or extra-items hint. + + Args: + hint: The type hint to specialize. + substitution: Type arguments by type parameter. + + Returns: + The specialized hint with type aliases resolved. + """ + if isinstance(hint, TypeVar): + hint = substitution.get(hint, hint) + elif substitution and (params := getattr(hint, "__parameters__", ())): + hint = _apply_type_params(hint, params, substitution) + return resolve_type_alias(hint) + + def _unionize(args: list[GenericType]) -> GenericType: if not args: return Any # pyright: ignore [reportReturnType] @@ -1296,41 +1329,47 @@ 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) + typed_dict = get_origin_og(cls) or cls + if not get_required_typed_dict_keys(typed_dict).issubset(obj): + return False + + extra_items_type = getattr(typed_dict, "__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. + # TypedDict rejects them regardless of the sentinel. extra_items_type = Any + elif extra_items_type is not Any: + extra_items_type = _specialize_typed_dict_hint( + extra_items_type, + _match_type_args(getattr(typed_dict, "__parameters__", ()), get_args(cls)), + ) + while get_origin_og(extra_items_type) in _TYPED_DICT_QUALIFIERS: + extra_items_type = get_args(extra_items_type)[0] + + is_closed = getattr(typed_dict, "__closed__", False) or extra_items_type in ( + typing.Never, + typing.NoReturn, + ) + if nested <= 0: + if not is_closed: + return True + field_names = _typed_dict_annotations(typed_dict) + return all(key in field_names for key in obj) + field_types = _get_typed_dict_field_types(cls, allow_undeclared=True) for key, value in obj.items(): - if is_closed and key not in key_names_to_values: + if is_closed and key not in field_types: + return False + if not _isinstance( + value, + field_types.get(key, extra_items_type), + nested=nested - 1, + treat_var_as_type=treat_var_as_type, + treat_mutable_obj_as_immutable=treat_mutable_obj_as_immutable, + ): return False - if nested: - if key in key_names_to_values: - expected_type = key_names_to_values[key] - if not _isinstance( - value, - expected_type, - nested=nested - 1, - treat_var_as_type=treat_var_as_type, - treat_mutable_obj_as_immutable=treat_mutable_obj_as_immutable, - ): - return False - else: - if not _isinstance( - value, - extra_items_type, - nested=nested - 1, - treat_var_as_type=treat_var_as_type, - treat_mutable_obj_as_immutable=treat_mutable_obj_as_immutable, - ): - return False - # required keys are all present - return required_keys.issubset(frozenset(obj)) + return True class _Unloaded: @@ -1447,19 +1486,19 @@ 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( - obj, - cls, - nested=nested - 1, - treat_var_as_type=treat_var_as_type, - treat_mutable_obj_as_immutable=treat_mutable_obj_as_immutable, - ) + if typing_extensions.is_typeddict(origin if origin is not None else cls): + if nested <= 0: return isinstance(obj, dict) + # A plain TypedDict consumes one level before checking field values. + return does_obj_satisfy_typed_dict( + obj, + cls, + nested=nested if origin is not None else nested - 1, + treat_var_as_type=treat_var_as_type, + treat_mutable_obj_as_immutable=treat_mutable_obj_as_immutable, + ) + if origin is None: # cls is a float if cls is float: return isinstance(obj, (float, int)) diff --git a/tests/units/reflex_base/utils/test_types.py b/tests/units/reflex_base/utils/test_types.py index 5017e021dcc..4c9502bc7ac 100644 --- a/tests/units/reflex_base/utils/test_types.py +++ b/tests/units/reflex_base/utils/test_types.py @@ -528,6 +528,8 @@ def test_get_required_typed_dict_keys_with_postponed_annotations(tmp_path, monke try: assert get_required_typed_dict_keys(module.Data) == {"name"} assert get_required_typed_dict_keys(module.Partial) == {"email", "phone"} + assert _isinstance({"name": "Ada"}, module.Data, nested=1) + assert not _isinstance({"phone": "555-0100"}, module.Partial, nested=1) finally: del sys.modules["postponed_typed_dicts"] @@ -626,6 +628,71 @@ class _GenericBase(TypedDict, Generic[_FieldT]): maybe: _FieldT | None +def test_isinstance_resolves_generic_typed_dict_fields(): + """Generic TypedDict specializations validate their resolved field types.""" + assert _isinstance({"value": "text", "maybe": None}, _GenericBase[str], nested=1) + assert _isinstance({"value": 1, "maybe": 2}, _GenericBase[int], nested=1) + assert not _isinstance({"value": 1, "maybe": None}, _GenericBase[str], nested=1) + assert not _isinstance( + {"value": "text", "maybe": None}, _GenericBase[int], nested=1 + ) + assert _isinstance({"value": 1, "maybe": None}, _GenericBase[int] | None, nested=1) + assert _isinstance(None, _GenericBase[int] | None, nested=1) + assert not _isinstance( + {"value": "text", "maybe": None}, _GenericBase[int] | None, nested=1 + ) + + +def test_isinstance_generic_typed_dict_at_depth_zero(): + """A depth-zero check recognizes generic TypedDicts as dictionaries.""" + value = {"value": "text", "maybe": None} + assert _isinstance(value, _GenericBase[str], nested=0) + assert not _isinstance([], _GenericBase[str], nested=0) + assert _isinstance([value], list[_GenericBase[str]], nested=1) + assert not _isinstance([[]], list[_GenericBase[str]], nested=1) + + +def test_isinstance_plain_typing_extensions_typed_dict(): + """A plain backport TypedDict follows the same depth rules as a stdlib one.""" + assert _isinstance({"name": "Ada"}, _SignupData, nested=0) + assert _isinstance({"name": "Ada", "email": "a@example.org"}, _SignupData, nested=1) + assert not _isinstance({"name": "Ada"}, _SignupData, nested=1) + assert not _isinstance({"name": 1, "email": "a@example.org"}, _SignupData, nested=2) + + +class _GenericExtraItems(TypedDict, Generic[_FieldT], extra_items=list[_FieldT]): + name: str + + +class _GenericReadOnlyExtraItems( + TypedDict, Generic[_FieldT], extra_items=ReadOnly[list[_FieldT]] +): + name: str + + +class _GenericNoExtraItems(TypedDict, Generic[_FieldT], extra_items=typing.Never): + value: _FieldT + + +@pytest.mark.parametrize("schema", [_GenericExtraItems, _GenericReadOnlyExtraItems]) +def test_isinstance_resolves_generic_typed_dict_extra_items(schema): + """Typed extra items use the same type arguments as named fields. + + Args: + schema: A generic TypedDict with writable or read-only extra items. + """ + assert _isinstance({"name": "a", "extra": [1]}, schema[int], nested=2) + assert not _isinstance({"name": "a", "extra": ["bad"]}, schema[int], nested=2) + + +def test_isinstance_rejects_extra_items_typed_as_never(): + """An extra-items type of Never disallows extra keys.""" + assert _isinstance({"value": 1}, _GenericNoExtraItems[int], nested=1) + assert not _isinstance( + {"value": 1, "extra": 2}, _GenericNoExtraItems[int], nested=1 + ) + + class _GenericMiddle(_GenericBase[list[_ItemT]], Generic[_ItemT]): flag: bool @@ -679,6 +746,9 @@ class Plain(Concrete): else: with pytest.raises(TypeError, match=r"typing_extensions\.TypedDict"): get_typed_dict_field_types(Plain) + assert _isinstance({"value": ["text"]}, Plain, nested=1) + assert _isinstance({"value": ["text"]}, Plain, nested=3) + assert not _isinstance({}, Plain, nested=1) class _Unresolved(TypedDict): diff --git a/tests/units/reflex_base/vars/test_base.py b/tests/units/reflex_base/vars/test_base.py index 32be1940590..4390b0dcfb4 100644 --- a/tests/units/reflex_base/vars/test_base.py +++ b/tests/units/reflex_base/vars/test_base.py @@ -17,7 +17,7 @@ from abc import ABC, abstractmethod from collections.abc import Iterable, Iterator, Mapping, Sequence from pathlib import Path -from typing import Any, ClassVar, Literal, Self, TypedDict, TypeVar +from typing import Any, ClassVar, Generic, Literal, Self, TypedDict, TypeVar from unittest import mock import pytest @@ -2701,6 +2701,36 @@ def as_ints(self) -> list[int]: assert any(f"{name}.items" in r.getMessage() for r in caplog.records) +_PayloadT = TypeVar("_PayloadT") + + +class _GenericPayload(TypedDict, Generic[_PayloadT]): + value: _PayloadT + + +@pytest.mark.usefixtures("restore_env_mode") +@pytest.mark.parametrize("env_mode", [constants.Env.DEV, constants.Env.PROD]) +def test_generic_typed_dict_state_assignment( + caplog: pytest.LogCaptureFixture, env_mode: constants.Env +): + """Accept valid specialized TypedDict assignments in both environment modes. + + Args: + caplog: Pytest log capture fixture. + env_mode: The environment mode for state type checking. + """ + + class AssignmentState(BaseState): + payload: _GenericPayload[str] = {"value": "initial"} + + environment.REFLEX_ENV_MODE.set(env_mode) + state = AssignmentState() + with caplog.at_level(logging.ERROR, logger="reflex_base.vars.base"): + state.payload = {"value": "updated"} + assert state.payload == {"value": "updated"} + assert caplog.messages == [] + + @pytest.mark.asyncio async def test_cached_async_computed_var_checks_return_type_on_recompute_only( monkeypatch: pytest.MonkeyPatch,