Coverage for src / dynapydantic / polymorphic.py: 100%
9 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-02-06 15:20 +0000
« prev ^ index » next coverage.py v7.12.0, created at 2026-02-06 15:20 +0000
1"""Definition for Polymorphic"""
3import typing as ty
5from .subclass_tracking_model import SubclassTrackingModel
7ModelT = ty.TypeVar("ModelT", bound=SubclassTrackingModel)
9if ty.TYPE_CHECKING: # pragma: no cover
10 Polymorphic = ty.Annotated[ModelT, ...]
11else:
13 class Polymorphic:
14 """Annotation used to mark a type as having duck-typing behavior
16 This annotation is only valid for SubclassTrackingModel's.
18 Similar to SerializeAsAny, a field annotated with this shall serialize as
19 according to its actual type, not the field annotation type. In addition,
20 parsing will function as if the field annotation type were the union of
21 all tracked subclasses.
22 """
24 def __class_getitem__(cls, item: ModelT) -> ty.Any: # noqa: ANN401
25 """Get the annotation for the pydantic field"""
26 if not isinstance(item, type):
27 msg = f"dynapydantic.Polymorphic must be given a type, not {item}"
28 raise TypeError(msg)
29 return ty.Annotated[item, SubclassTrackingModel.PydanticAdaptor]