Unwrap `Annotated` type hints in type resolution and comparison
Type of change
- Bug fix (non-breaking change which fixes an issue)
Description
This PR fixes type resolution and comparison to properly handle Annotated type hints, which are commonly used in pydantic for discriminated unions and other metadata-carrying types.
Problem: When a var is typed with a pydantic discriminated union like Annotated[Cat | Dog, Field(discriminator="kind")], reading it from a state var (e.g., colors["red"] where colors: dict[str, Annotated[...]]) would fail with "Unsupported type ... for guess_type" because the type resolution logic didn't unwrap the Annotated wrapper to see the actual union type.
Solution:
- Added
_annotated_origin()helper to safely extract the wrapped type fromAnnotated[X, ...]hints - Updated
resolve_type_alias()to unwrapAnnotatedbefore resolving aliases, handling cases likeAnnotated[SomeAlias, ...] - Updated
typehint_issubclass()to unwrapAnnotatedon both sides of the comparison so thatAnnotated[int, "meta"]correctly compares asint
The metadata (pydantic discriminators, validators, units, etc.) is never part of the type Reflex reasons about, so it's safely discarded during type inspection.
Changes
-
packages/reflex-base/src/reflex_base/utils/types.py:- Added
_annotated_origin()helper function - Modified
resolve_type_alias()to unwrapAnnotatedhints before alias resolution - Modified
typehint_issubclass()to unwrapAnnotatedon both sides of comparison
- Added
-
tests/units/reflex_base/utils/test_types.py:- Added
test_resolve_type_alias_unwraps_annotated()covering nested annotations and aliases - Added
test_typehint_issubclass_unwraps_annotated()covering comparison with annotations - Added
test_isinstance_unwraps_annotated()covering instance validation
- Added
-
tests/units/vars/test_object.py:- Added
test_annotated_value_type_is_unwrapped()testing pydantic discriminated unions in dict values - Added
test_annotated_var_type_is_unwrapped()testingAnnotatedon var's own type
- Added
-
packages/reflex-base/news/+annotated-type-hints.bugfix.md:- Added changelog fragment documenting the fix
Testing
All new tests pass and cover:
- Unwrapping nested
Annotatedhints - Unwrapping
Annotatedaround type aliases - Type comparison with
Annotatedon either side - Instance validation against
Annotatedtypes - Real-world pydantic discriminated union scenario (reading from dict var)