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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
State vars typed with a `typing_extensions.TypedDict` now get typed key access and an error for unknown keys, and assignments to them are checked against the field types, same as `typing.TypedDict`.
9 changes: 4 additions & 5 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 @@ -495,7 +494,7 @@ def get_typed_dict_field_types(typed_dict: Any) -> dict[str, Any]:
annotations = _typed_dict_annotations(origin)
for base in typing_extensions.get_original_bases(origin):
base_origin = get_origin_og(base) or base
if typing_extensions.is_typeddict(base_origin):
if is_typeddict(base_origin):
if base is base_origin and (
params := getattr(base_origin, "__parameters__", ())
):
Expand Down Expand Up @@ -1118,7 +1117,7 @@ def _get_column_access_type(cls: type, name: str) -> GenericType | None:
and (declared := _get_mapped_annotation(cls, name)) is not None
and (
(get_origin(declared) or declared) is type_
or (type_ is dict and typing_extensions.is_typeddict(declared))
or (type_ is dict and is_typeddict(declared))
)
):
type_ = declared
Expand Down Expand Up @@ -1219,7 +1218,7 @@ def get_attribute_access_type(
return unionize(
*(get_attribute_access_type(arg, name) for arg in get_args(cls))
)
if is_generic_alias(cls) and typing_extensions.is_typeddict(get_origin_og(cls)):
if is_generic_alias(cls) and is_typeddict(get_origin_og(cls)):
# A specialized generic TypedDict: its fields name the type parameters.
return get_typed_dict_field_types(cls).get(name)
if isinstance(cls, type):
Expand Down
17 changes: 7 additions & 10 deletions packages/reflex-base/src/reflex_base/vars/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,9 @@
import typing
from collections.abc import Mapping
from importlib.util import find_spec
from typing import (
Any,
NoReturn,
TypeVar,
get_args,
get_type_hints,
is_typeddict,
overload,
)
from typing import Any, NoReturn, TypeVar, get_args, get_type_hints, overload
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

from typing_extensions import is_typeddict

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Known fields become unreadable

The new import sends bare typing_extensions.TypedDict fields through get_attribute_access_type, which resolves every annotation at once. If one field names a type imported only under TYPE_CHECKING, reading even a different, fully defined field now raises VarAttributeError. Previously that read returned an Any-typed var, so this can break existing app expressions.

Use get_typed_dict_field_types for TypedDict field lookup. It already keeps known field types and treats unresolved names as Any.


from reflex_base.utils import types
from reflex_base.utils.exceptions import VarAttributeError
Expand Down Expand Up @@ -61,7 +55,10 @@ def _determine_value_type(var_type: GenericType):
if arg is not type(None)
])

if is_typeddict(origin_var_type) or dataclasses.is_dataclass(origin_var_type):
if is_typeddict(origin_var_type):
return unionize(*types.get_typed_dict_field_types(var_type).values())

if dataclasses.is_dataclass(origin_var_type):
annotations = get_type_hints(origin_var_type)
return unionize(*annotations.values())

Expand Down
25 changes: 25 additions & 0 deletions tests/units/utils/test_types.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from typing import Any, Literal, TypedDict

import pytest
import typing_extensions
from reflex_base.utils import types
from reflex_base.vars.base import Var

Expand Down Expand Up @@ -136,3 +137,27 @@ class UserInfoTotal(TypedDict, total=True):
)
def test_isinstance(value, cls, expected: bool) -> None:
assert types._isinstance(value, cls, nested=2, treat_var_as_type=True) == expected


class ExtensionsUserInfo(typing_extensions.TypedDict, total=False):
"""A sample typed dict from typing_extensions."""

sub: str
name: str


@pytest.mark.parametrize(
("value", "expected"),
[
({"sub": "123", "name": "John"}, True),
({"sub": 123}, False),
],
)
def test_isinstance_typing_extensions_typed_dict(value: dict, expected: bool) -> None:
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
"""Check that _isinstance validates typing_extensions TypedDict values.

Args:
value: The value to check.
expected: Whether the value matches the TypedDict.
"""
assert types._isinstance(value, ExtensionsUserInfo, nested=2) == expected
31 changes: 31 additions & 0 deletions tests/units/vars/test_object.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import dataclasses
import typing
from collections.abc import Sequence
from typing import Annotated, Any, Literal, Union, assert_type

import pytest
import typing_extensions
from reflex_base.utils import serializers
from reflex_base.utils.exceptions import VarAttributeError
from reflex_base.utils.imports import ImportVar
Expand Down Expand Up @@ -612,3 +614,32 @@ class UnionState(rx.State):

with pytest.raises(VarAttributeError, match="union type"):
_ = UnionState.item.label


class _TypingPoint(typing.TypedDict):
"""A TypedDict from the typing module."""

x: int
name: str


class _ExtensionsPoint(typing_extensions.TypedDict):
"""A TypedDict from typing_extensions."""

x: int
name: str


@pytest.mark.parametrize("point_type", [_TypingPoint, _ExtensionsPoint])
def test_typed_dict_key_access(point_type: type) -> None:
"""Keys of a TypedDict var have the field types, whichever TypedDict defines it.

Args:
point_type: The TypedDict class typing the var.
"""
point = Var(_js_expr="point", _var_type=point_type).guess_type()
assert isinstance(point, ObjectVar)
assert point["x"]._var_type is int
assert point["name"]._var_type is str
with pytest.raises(VarAttributeError):
_ = point["missing"]