Coverage for src/dynapydantic/annotations.py: 100%
68 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-16 12:39 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-16 12:39 +0000
1"""Custom annotations for dynapydantic"""
3import enum
4import typing as ty
5import warnings
7from pydantic import GetCoreSchemaHandler, PydanticSchemaGenerationError
8from pydantic_core import core_schema
10from .free_funcs import union
11from .subclass_tracking_model import (
12 SubclassTrackingModel,
13 ValidationTimeAdapter,
14)
15from .tracking_group import TrackingGroup
16from .union_mode import UnionRealization
18ModelT = ty.TypeVar("ModelT", bound=SubclassTrackingModel)
21class ModelConstructionTimeAdapter:
22 """Pydantic type adapter for SubclassTrackingModel"""
24 @staticmethod
25 def __get_pydantic_core_schema__(
26 source_type: type[SubclassTrackingModel],
27 handler: GetCoreSchemaHandler,
28 ) -> core_schema.CoreSchema:
29 """Get the pydantic schema for this type"""
30 return handler(union(source_type))
33if ty.TYPE_CHECKING: # pragma: no cover
34 ModelConstructionTimeUnion = ty.Annotated[ModelT, ...]
35 ValidationTimeUnion = ty.Annotated[ModelT, ...]
36else:
38 class ModelConstructionTimeUnion:
39 """Override the union realization to model-construction time.
41 Use this annotation to wrap a type inside of a `Polymorphic`
42 annotation to override the default union realization mode for a field.
43 """
45 def __class_getitem__(
46 cls,
47 item: type[ModelT],
48 ) -> ty.Annotated[type[ModelT], ...]:
49 """Produce a custom annotation."""
50 return ty.Annotated[item, _MODEL_CONSTRUCTION_TIME_UNION]
52 class ValidationTimeUnion:
53 """Override the union realization to validation time.
55 Use this annotation to wrap a type inside of a `Polymorphic`
56 annotation to override the default union realization mode for a field.
57 """
59 def __class_getitem__(
60 cls,
61 item: type[ModelT],
62 ) -> ty.Annotated[type[ModelT], ...]:
63 """Produce a custom annotation."""
64 return ty.Annotated[item, _VALIDATION_TIME_UNION]
67class _UnionRealizationOverride(enum.Enum):
68 """Private, stable markers for union realization overrides."""
70 MODEL_CONSTRUCTION = enum.auto()
71 VALIDATION = enum.auto()
74_MODEL_CONSTRUCTION_TIME_UNION = _UnionRealizationOverride.MODEL_CONSTRUCTION
75_VALIDATION_TIME_UNION = _UnionRealizationOverride.VALIDATION
78if ty.TYPE_CHECKING: # pragma: no cover
79 Polymorphic = ty.Annotated[ModelT, ...]
80else:
82 class Polymorphic:
83 """Annotation used to mark a type as having duck-typing behavior
85 This annotation is only valid for SubclassTrackingModel's.
87 Similar to SerializeAsAny, a field annotated with this shall serialize as
88 according to its actual type, not the field annotation type. In addition,
89 parsing will function as if the field annotation type were the union of
90 all tracked subclasses.
91 """
93 def __class_getitem__(
94 cls,
95 item: type[ModelT],
96 ) -> ty.Annotated[type[ModelT], ...]:
97 """Get the annotation for the pydantic field"""
98 if isinstance(item, tuple):
99 if len(item) > 2: # noqa: PLR2004
100 msg = (
101 "dynapydantic.Polymorphic takes 1 or 2 arguments "
102 f"({len(item)} given)"
103 )
104 raise TypeError(msg)
105 if len(item) > 1:
106 msg = (
107 "The multi-parameter form of Polymorphic is deprecated and "
108 "will be removed in 0.9.0 or 1.0.0, whichever comes first. "
109 "Instead use dynapydantic.ModelConstructionTimeUnion or "
110 "dynapydantic.ValidationTimeUnion."
111 )
112 warnings.warn(msg, FutureWarning, stacklevel=2)
114 return _polymorphic_cgi(*item)
115 return _polymorphic_cgi(item)
118def _polymorphic_cgi(
119 cls: type[ModelT] | ty.Annotated[type[ModelT], ...],
120 union_realization: UnionRealization | str | None = None,
121) -> ty.Annotated[type[ModelT], ...]:
122 is_annotated = ty.get_origin(cls) is ty.Annotated
123 annotated_metadata: tuple[object, ...] = ()
124 if is_annotated:
125 args = ty.get_args(cls)
126 cls = args[0]
127 annotated_metadata = args[1:]
129 if not (isinstance(cls, type) and issubclass(cls, SubclassTrackingModel)):
130 msg = f"Polymorphic was given {cls}, which was not a SubclassTrackingModel."
131 raise PydanticSchemaGenerationError(msg)
133 cfg = cls.__DYNAPYDANTIC_STM_CONFIG__
134 if union_realization is not None:
135 union_realization = UnionRealization(union_realization)
136 elif is_annotated:
137 mc = any(a is _MODEL_CONSTRUCTION_TIME_UNION for a in annotated_metadata)
138 val = any(a is _VALIDATION_TIME_UNION for a in annotated_metadata)
139 if mc and val:
140 msg = (
141 "Conflicting union realization overrides detected. Specify at "
142 "most one of: ModelConstructionTimeUnion, ValidationTimeUnion."
143 )
144 raise TypeError(msg)
145 if mc:
146 union_realization = UnionRealization.MODEL_CONSTRUCTION
147 elif val:
148 union_realization = UnionRealization.VALIDATION
149 else:
150 union_realization = cfg.union_realization
151 else:
152 union_realization = cfg.union_realization
153 adapter = (
154 ValidationTimeAdapter
155 if union_realization == UnionRealization.VALIDATION
156 else ModelConstructionTimeAdapter
157 )
158 metadata = tuple(
159 item
160 for item in annotated_metadata
161 if item is not _MODEL_CONSTRUCTION_TIME_UNION
162 and item is not _VALIDATION_TIME_UNION
163 )
164 return ty.Annotated[cls, *metadata, adapter] # type: ignore[bad-return]
167_UnionT = ty.TypeVar("_UnionT", bound=TrackingGroup | SubclassTrackingModel)
170class Union(ty.Generic[_UnionT]):
171 """Annotation used to get the union out of a dynapydantic entity
173 This annotation is primarily used for using the union of all models in
174 a `TrackingGroup` as a field annotation. It can be used with
175 `SubclassTrackingModel`, but in general, `Polymorphic` is preferable.
176 """
178 @ty.overload
179 def __class_getitem__(cls, item: type[ModelT]) -> type[ModelT]: ...
181 @ty.overload
182 def __class_getitem__(cls, item: TrackingGroup) -> ty.Any: ... # noqa: ANN401
184 def __class_getitem__(cls, item: TrackingGroup | type[ModelT]) -> object:
185 """Return the union"""
186 return union(item)