Coverage for src / dynapydantic / polymorphic.py: 100%

9 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-04-06 21:55 +0000

1"""Definition for Polymorphic""" 

2 

3import typing as ty 

4 

5from .subclass_tracking_model import SubclassTrackingModel 

6 

7ModelT = ty.TypeVar("ModelT", bound=SubclassTrackingModel) 

8 

9if ty.TYPE_CHECKING: # pragma: no cover 

10 Polymorphic = ty.Annotated[ModelT, ...] 

11else: 

12 

13 class Polymorphic: 

14 """Annotation used to mark a type as having duck-typing behavior 

15 

16 This annotation is only valid for SubclassTrackingModel's. 

17 

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 """ 

23 

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]