Unwrap `Annotated` type hints in type resolution and comparison

Merged
MA
3mo ago
+135-5

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:

  1. Added _annotated_origin() helper to safely extract the wrapped type from Annotated[X, ...] hints
  2. Updated resolve_type_alias() to unwrap Annotated before resolving aliases, handling cases like Annotated[SomeAlias, ...]
  3. Updated typehint_issubclass() to unwrap Annotated on both sides of the comparison so that Annotated[int, "meta"] correctly compares as int

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 unwrap Annotated hints before alias resolution
    • Modified typehint_issubclass() to unwrap Annotated on both sides of comparison
  • 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
  • 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() testing Annotated on var's own type
  • packages/reflex-base/news/+annotated-type-hints.bugfix.md:

    • Added changelog fragment documenting the fix

Testing

All new tests pass and cover:

  • Unwrapping nested Annotated hints
  • Unwrapping Annotated around type aliases
  • Type comparison with Annotated on either side
  • Instance validation against Annotated types
  • Real-world pydantic discriminated union scenario (reading from dict var)

https://claude.ai/code/session_01HxGHX7e4xnf1ehT1H1h6Nz