Coverage for pydantic / type_adapter.py: 94.74%
165 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
1"""Type adapter specification."""
3from __future__ import annotations as _annotations 1amnbcdeopfghsiqrjkl
5import sys 1amnbcdeopfghsiqrjkl
6import types 1amnbcdeopfghsiqrjkl
7from collections.abc import Callable, Iterable 1amnbcdeopfghsiqrjkl
8from dataclasses import is_dataclass 1amnbcdeopfghsiqrjkl
9from types import FrameType 1amnbcdeopfghsiqrjkl
10from typing import ( 1amnbcdeopfghsiqrjkl
11 Any,
12 Generic,
13 Literal,
14 TypeVar,
15 cast,
16 final,
17)
19from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator, Some 1amnbcdeopfghsiqrjkl
20from typing_extensions import ParamSpec, TypeForm, is_typeddict 1amnbcdeopfghsiqrjkl
22from pydantic.errors import PydanticUserError 1amnbcdeopfghsiqrjkl
23from pydantic.main import BaseModel, IncEx 1amnbcdeopfghsiqrjkl
25from ._internal import _config, _generate_schema, _mock_val_ser, _namespace_utils, _repr, _typing_extra, _utils 1amnbcdeopfghsiqrjkl
26from .config import ConfigDict, ExtraValues 1amnbcdeopfghsiqrjkl
27from .errors import PydanticUndefinedAnnotation 1amnbcdeopfghsiqrjkl
28from .json_schema import ( 1amnbcdeopfghsiqrjkl
29 DEFAULT_REF_TEMPLATE,
30 GenerateJsonSchema,
31 JsonSchemaKeyT,
32 JsonSchemaMode,
33 JsonSchemaValue,
34)
35from .plugin._schema_validator import PluggableSchemaValidator, create_schema_validator 1amnbcdeopfghsiqrjkl
37T = TypeVar('T') 1amnbcdeopfghsiqrjkl
38R = TypeVar('R') 1amnbcdeopfghsiqrjkl
39P = ParamSpec('P') 1amnbcdeopfghsiqrjkl
40TypeAdapterT = TypeVar('TypeAdapterT', bound='TypeAdapter') 1amnbcdeopfghsiqrjkl
43def _getattr_no_parents(obj: Any, attribute: str) -> Any: 1amnbcdeopfghsiqrjkl
44 """Returns the attribute value without attempting to look up attributes from parent types."""
45 if hasattr(obj, '__dict__'): 1amnbcdeopfghiqrjkl
46 try: 1amnbcdeopfghiqrjkl
47 return obj.__dict__[attribute] 1amnbcdeopfghiqrjkl
48 except KeyError: 1amnbcdeopfghiqrjkl
49 pass 1amnbcdeopfghiqrjkl
51 slots = getattr(obj, '__slots__', None) 1amnbcdeopfghiqrjkl
52 if slots is not None and attribute in slots: 52 ↛ 53line 52 didn't jump to line 53 because the condition on line 52 was never true1amnbcdeopfghiqrjkl
53 return getattr(obj, attribute)
54 else:
55 raise AttributeError(attribute) 1amnbcdeopfghiqrjkl
58def _type_has_config(type_: Any) -> bool: 1amnbcdeopfghsiqrjkl
59 """Returns whether the type has config."""
60 type_ = _typing_extra.annotated_type(type_) or type_ 1amnbcdeopfghiqrjkl
61 try: 1amnbcdeopfghiqrjkl
62 return issubclass(type_, BaseModel) or is_dataclass(type_) or is_typeddict(type_) 1amnbcdeopfghiqrjkl
63 except TypeError: 1amnbcdeopfghiqrjkl
64 # type is not a class
65 return False 1amnbcdeopfghiqrjkl
68@final 1amnbcdeopfghsiqrjkl
69class TypeAdapter(Generic[T]): 1amnbcdeopfghsiqrjkl
70 """!!! abstract "Usage Documentation"
71 [`TypeAdapter`](../concepts/type_adapter.md)
73 Type adapters provide a flexible way to perform validation and serialization based on a Python type.
75 A `TypeAdapter` instance exposes some of the functionality from `BaseModel` instance methods
76 for types that do not have such methods (such as dataclasses, primitive types, and more).
78 **Note:** `TypeAdapter` instances are not types, and cannot be used as type annotations for fields.
80 Args:
81 type: The type associated with the `TypeAdapter`.
82 config: Configuration for the `TypeAdapter`, should be a dictionary conforming to
83 [`ConfigDict`][pydantic.config.ConfigDict].
85 !!! note
86 You cannot provide a configuration when instantiating a `TypeAdapter` if the type you're using
87 has its own config that cannot be overridden (ex: `BaseModel`, `TypedDict`, and `dataclass`). A
88 [`type-adapter-config-unused`](../errors/usage_errors.md#type-adapter-config-unused) error will
89 be raised in this case.
90 _parent_depth: Depth at which to search for the [parent frame][frame-objects]. This frame is used when
91 resolving forward annotations during schema building, by looking for the globals and locals of this
92 frame. Defaults to 2, which will result in the frame where the `TypeAdapter` was instantiated.
94 !!! note
95 This parameter is named with an underscore to suggest its private nature and discourage use.
96 It may be deprecated in a minor version, so we only recommend using it if you're comfortable
97 with potential change in behavior/support. It's default value is 2 because internally,
98 the `TypeAdapter` class makes another call to fetch the frame.
99 module: The module that passes to plugin if provided.
101 Attributes:
102 core_schema: The core schema for the type.
103 validator: The schema validator for the type.
104 serializer: The schema serializer for the type.
105 pydantic_complete: Whether the core schema for the type is successfully built.
107 ??? info "Namespace management nuances and implementation details"
109 Here, we collect some notes on namespace management, and subtle differences from `BaseModel`:
111 `BaseModel` uses its own `__module__` to find out where it was defined
112 and then looks for symbols to resolve forward references in those globals.
113 On the other hand, `TypeAdapter` can be initialized with arbitrary objects,
114 which may not be types and thus do not have a `__module__` available.
115 So instead we look at the globals in our parent stack frame.
117 It is expected that the `ns_resolver` passed to this function will have the correct
118 namespace for the type we're adapting. See the source code for `TypeAdapter.__init__`
119 and `TypeAdapter.rebuild` for various ways to construct this namespace.
121 This works for the case where this function is called in a module that
122 has the target of forward references in its scope, but
123 does not always work for more complex cases.
125 For example, take the following:
127 ```python {title="a.py"}
128 IntList = list[int]
129 OuterDict = dict[str, 'IntList']
130 ```
132 ```python {test="skip" title="b.py"}
133 from a import OuterDict
135 from pydantic import TypeAdapter
137 IntList = int # replaces the symbol the forward reference is looking for
138 v = TypeAdapter(OuterDict)
139 v({'x': 1}) # should fail but doesn't
140 ```
142 If `OuterDict` were a `BaseModel`, this would work because it would resolve
143 the forward reference within the `a.py` namespace.
144 But `TypeAdapter(OuterDict)` can't determine what module `OuterDict` came from.
146 In other words, the assumption that _all_ forward references exist in the
147 module we are being called from is not technically always true.
148 Although most of the time it is and it works fine for recursive models and such,
149 `BaseModel`'s behavior isn't perfect either and _can_ break in similar ways,
150 so there is no right or wrong between the two.
152 But at the very least this behavior is _subtly_ different from `BaseModel`'s.
153 """
155 core_schema: CoreSchema 1amnbcdeopfghsiqrjkl
156 validator: SchemaValidator | PluggableSchemaValidator 1amnbcdeopfghsiqrjkl
157 serializer: SchemaSerializer 1amnbcdeopfghsiqrjkl
158 pydantic_complete: bool 1amnbcdeopfghsiqrjkl
160 def __init__( 1amnbcdeopfghsiqrjkl
161 self,
162 type: TypeForm[T],
163 *,
164 config: ConfigDict | None = None,
165 _parent_depth: int = 2,
166 module: str | None = None,
167 ) -> None:
168 if _type_has_config(type) and config is not None: 1amnbcdeopfghiqrjkl
169 raise PydanticUserError( 1amnbcdeopfghiqrjkl
170 'Cannot use `config` when the type is a BaseModel, dataclass or TypedDict.'
171 ' These types can have their own config and setting the config via the `config`'
172 ' parameter to TypeAdapter will not override it, thus the `config` you passed to'
173 ' TypeAdapter becomes meaningless, which is probably not what you want.',
174 code='type-adapter-config-unused',
175 )
177 self._type = type 1amnbcdeopfghiqrjkl
178 self._config = config 1amnbcdeopfghiqrjkl
179 self._parent_depth = _parent_depth 1amnbcdeopfghiqrjkl
180 self.pydantic_complete = False 1amnbcdeopfghiqrjkl
182 parent_frame = self._fetch_parent_frame() 1amnbcdeopfghiqrjkl
183 if isinstance(type, types.FunctionType): 1amnbcdeopfghiqrjkl
184 # Special case functions, which are *not* pushed to the `NsResolver` stack and without this special case
185 # would only have access to the parent namespace where the `TypeAdapter` was instantiated (if the function is defined
186 # in another module, we need to look at that module's globals).
187 if parent_frame is not None: 1amnbcdeopfghiqrjkl
188 # `f_locals` is the namespace where the type adapter was instantiated (~ to `f_globals` if at the module level):
189 parent_ns = parent_frame.f_locals 1amnbcdeopfghiqrjkl
190 else: # pragma: no cover
191 parent_ns = None
192 globalns, localns = _namespace_utils.ns_for_function( 1amnbcdeopfghiqrjkl
193 type,
194 parent_namespace=parent_ns,
195 )
196 parent_namespace = None 1amnbcdeopfghiqrjkl
197 else:
198 if parent_frame is not None: 1amnbcdeopfghiqrjkl
199 globalns = parent_frame.f_globals 1amnbcdeopfghiqrjkl
200 # Do not provide a local ns if the type adapter happens to be instantiated at the module level:
201 localns = parent_frame.f_locals if parent_frame.f_locals is not globalns else {} 1amnbcdeopfghiqrjkl
202 else: # pragma: no cover
203 globalns = {}
204 localns = {}
205 parent_namespace = localns 1amnbcdeopfghiqrjkl
207 self._module_name = module or cast(str, globalns.get('__name__', '')) 1amnbcdeopfghiqrjkl
208 self._init_core_attrs( 1amnbcdeopfghiqrjkl
209 ns_resolver=_namespace_utils.NsResolver(
210 namespaces_tuple=_namespace_utils.NamespacesTuple(locals=localns, globals=globalns),
211 parent_namespace=parent_namespace,
212 ),
213 force=False,
214 )
216 def _fetch_parent_frame(self) -> FrameType | None: 1amnbcdeopfghsiqrjkl
217 frame = sys._getframe(self._parent_depth) 1amnbcdeopfghiqrjkl
218 if frame.f_globals.get('__name__') == 'typing': 1amnbcdeopfghiqrjkl
219 # Because `TypeAdapter` is generic, explicitly parametrizing the class results
220 # in a `typing._GenericAlias` instance, which proxies instantiation calls to the
221 # "real" `TypeAdapter` class and thus adding an extra frame to the call. To avoid
222 # pulling anything from the `typing` module, use the correct frame (the one before):
223 return frame.f_back 1amnbcdeopfghiqrjkl
225 return frame 1amnbcdeopfghiqrjkl
227 def _init_core_attrs( 1amnbcdeopfghsiqrjkl
228 self, ns_resolver: _namespace_utils.NsResolver, force: bool, raise_errors: bool = False
229 ) -> bool:
230 """Initialize the core schema, validator, and serializer for the type.
232 Args:
233 ns_resolver: The namespace resolver to use when building the core schema for the adapted type.
234 force: Whether to force the construction of the core schema, validator, and serializer.
235 If `force` is set to `False` and `_defer_build` is `True`, the core schema, validator, and serializer will be set to mocks.
236 raise_errors: Whether to raise errors if initializing any of the core attrs fails.
238 Returns:
239 `True` if the core schema, validator, and serializer were successfully initialized, otherwise `False`.
241 Raises:
242 PydanticUndefinedAnnotation: If `PydanticUndefinedAnnotation` occurs in`__get_pydantic_core_schema__`
243 and `raise_errors=True`.
244 """
245 if not force and self._defer_build: 1amnbcdeopfghiqrjkl
246 _mock_val_ser.set_type_adapter_mocks(self) 1amnbcdeopfghiqrjkl
247 self.pydantic_complete = False 1amnbcdeopfghiqrjkl
248 return False 1amnbcdeopfghiqrjkl
250 try: 1amnbcdeopfghiqrjkl
251 self.core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') 1amnbcdeopfghiqrjkl
252 self.validator = _getattr_no_parents(self._type, '__pydantic_validator__') 1amnbcdeopfghiqrjkl
253 self.serializer = _getattr_no_parents(self._type, '__pydantic_serializer__') 1amnbcdeopfghiqrjkl
255 # TODO: we don't go through the rebuild logic here directly because we don't want
256 # to repeat all of the namespace fetching logic that we've already done
257 # so we simply skip to the block below that does the actual schema generation
258 if ( 1abcdefghijkl
259 isinstance(self.core_schema, _mock_val_ser.MockCoreSchema)
260 or isinstance(self.validator, _mock_val_ser.MockValSer)
261 or isinstance(self.serializer, _mock_val_ser.MockValSer)
262 ):
263 raise AttributeError() 1amnbcdeopfghiqrjkl
264 except AttributeError: 1amnbcdeopfghiqrjkl
265 config_wrapper = _config.ConfigWrapper(self._config) 1amnbcdeopfghiqrjkl
267 schema_generator = _generate_schema.GenerateSchema(config_wrapper, ns_resolver=ns_resolver) 1amnbcdeopfghiqrjkl
269 try: 1amnbcdeopfghiqrjkl
270 core_schema = schema_generator.generate_schema(self._type) 1amnbcdeopfghiqrjkl
271 except PydanticUndefinedAnnotation: 1amnbcdeopfghiqrjkl
272 if raise_errors: 1amnbcdeopfghiqrjkl
273 raise 1amnbcdeopfghiqrjkl
274 _mock_val_ser.set_type_adapter_mocks(self) 1amnbcdeopfghiqrjkl
275 return False 1amnbcdeopfghiqrjkl
277 try: 1amnbcdeopfghiqrjkl
278 self.core_schema = schema_generator.clean_schema(core_schema) 1amnbcdeopfghiqrjkl
279 except _generate_schema.InvalidSchemaError:
280 _mock_val_ser.set_type_adapter_mocks(self)
281 return False
283 core_config = config_wrapper.core_config(None) 1amnbcdeopfghiqrjkl
285 self.validator = create_schema_validator( 1amnbcdeopfghiqrjkl
286 schema=self.core_schema,
287 schema_type=self._type,
288 schema_type_module=self._module_name,
289 schema_type_name=str(self._type),
290 schema_kind='TypeAdapter',
291 config=core_config,
292 plugin_settings=config_wrapper.plugin_settings,
293 )
294 self.serializer = SchemaSerializer(self.core_schema, core_config) 1amnbcdeopfghiqrjkl
296 self.pydantic_complete = True 1amnbcdeopfghiqrjkl
297 return True 1amnbcdeopfghiqrjkl
299 @property 1amnbcdeopfghsiqrjkl
300 def _defer_build(self) -> bool: 1amnbcdeopfghsiqrjkl
301 config = self._config if self._config is not None else self._model_config 1amnbcdeopfghiqrjkl
302 if config: 1amnbcdeopfghiqrjkl
303 return config.get('defer_build') is True 1amnbcdeopfghiqrjkl
304 return False 1amnbcdeopfghiqrjkl
306 @property 1amnbcdeopfghsiqrjkl
307 def _model_config(self) -> ConfigDict | None: 1amnbcdeopfghsiqrjkl
308 type_: Any = _typing_extra.annotated_type(self._type) or self._type # Eg FastAPI heavily uses Annotated 1amnbcdeopfghiqrjkl
309 if _utils.lenient_issubclass(type_, BaseModel): 1amnbcdeopfghiqrjkl
310 return type_.model_config 1amnbcdeopfghiqrjkl
311 return getattr(type_, '__pydantic_config__', None) 1amnbcdeopfghiqrjkl
313 def __repr__(self) -> str: 1amnbcdeopfghsiqrjkl
314 return f'TypeAdapter({_repr.display_as_type(self._type)})' 1amnbcdeopfghiqrjkl
316 def rebuild( 1amnbcdeopfghsiqrjkl
317 self,
318 *,
319 force: bool = False,
320 raise_errors: bool = True,
321 _parent_namespace_depth: int = 2,
322 _types_namespace: _namespace_utils.MappingNamespace | None = None,
323 ) -> bool | None:
324 """Try to rebuild the pydantic-core schema for the adapter's type.
326 This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
327 the initial attempt to build the schema, and automatic rebuilding fails.
329 Args:
330 force: Whether to force the rebuilding of the type adapter's schema, defaults to `False`.
331 raise_errors: Whether to raise errors, defaults to `True`.
332 _parent_namespace_depth: Depth at which to search for the [parent frame][frame-objects]. This
333 frame is used when resolving forward annotations during schema rebuilding, by looking for
334 the locals of this frame. Defaults to 2, which will result in the frame where the method
335 was called.
336 _types_namespace: An explicit types namespace to use, instead of using the local namespace
337 from the parent frame. Defaults to `None`.
339 Returns:
340 Returns `None` if the schema is already "complete" and rebuilding was not required.
341 If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
342 """
343 if not force and self.pydantic_complete: 343 ↛ 344line 343 didn't jump to line 344 because the condition on line 343 was never true1amnbcdeopfghiqrjkl
344 return None
346 if _types_namespace is not None: 346 ↛ 347line 346 didn't jump to line 347 because the condition on line 346 was never true1amnbcdeopfghiqrjkl
347 rebuild_ns = _types_namespace
348 elif _parent_namespace_depth > 0: 348 ↛ 351line 348 didn't jump to line 351 because the condition on line 348 was always true1amnbcdeopfghiqrjkl
349 rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {} 1amnbcdeopfghiqrjkl
350 else:
351 rebuild_ns = {}
353 # we have to manually fetch globals here because there's no type on the stack of the NsResolver
354 # and so we skip the globalns = get_module_ns_of(typ) call that would normally happen
355 globalns = sys._getframe(max(_parent_namespace_depth - 1, 1)).f_globals 1amnbcdeopfghiqrjkl
356 ns_resolver = _namespace_utils.NsResolver( 1amnbcdeopfghiqrjkl
357 namespaces_tuple=_namespace_utils.NamespacesTuple(locals=rebuild_ns, globals=globalns),
358 parent_namespace=rebuild_ns,
359 )
360 return self._init_core_attrs(ns_resolver=ns_resolver, force=True, raise_errors=raise_errors) 1amnbcdeopfghiqrjkl
362 def validate_python( 1amnbcdeopfghsiqrjkl
363 self,
364 object: Any,
365 /,
366 *,
367 strict: bool | None = None,
368 extra: ExtraValues | None = None,
369 from_attributes: bool | None = None,
370 context: Any | None = None,
371 experimental_allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
372 by_alias: bool | None = None,
373 by_name: bool | None = None,
374 ) -> T:
375 """Validate a Python object against the model.
377 A [`ValidationError`][pydantic_core.ValidationError] reports the rejected locations and values.
378 If you record validations with [Logfire](../integrations/logfire.md), the complete object and trace
379 context are retained alongside the error — `TypeAdapter` validations are captured the same way as
380 model validations (see [Troubleshooting validation errors](../errors/troubleshooting.md)).
382 Args:
383 object: The Python object to validate against the model.
384 strict: Whether to strictly check types.
385 extra: Whether to ignore, allow, or forbid extra data during model validation.
386 See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
387 from_attributes: Whether to extract data from object attributes.
388 context: Additional context to pass to the validator.
389 experimental_allow_partial: **Experimental** whether to enable
390 [partial validation](../concepts/experimental.md#partial-validation), e.g. to process streams.
391 * False / 'off': Default behavior, no partial validation.
392 * True / 'on': Enable partial validation.
393 * 'trailing-strings': Enable partial validation and allow trailing strings in the input.
394 by_alias: Whether to use the field's alias when validating against the provided input data.
395 by_name: Whether to use the field's name when validating against the provided input data.
397 !!! note
398 When using `TypeAdapter` with a Pydantic `dataclass`, the use of the `from_attributes`
399 argument is not supported.
401 Returns:
402 The validated object.
403 """
404 if by_alias is False and by_name is not True: 1amnbcdeopfghiqrjkl
405 raise PydanticUserError( 1amnbcdeopfghiqrjkl
406 'At least one of `by_alias` or `by_name` must be set to True.',
407 code='validate-by-alias-and-name-false',
408 )
410 return self.validator.validate_python( 1amnbcdeopfghiqrjkl
411 object,
412 strict=strict,
413 extra=extra,
414 from_attributes=from_attributes,
415 context=context,
416 allow_partial=experimental_allow_partial,
417 by_alias=by_alias,
418 by_name=by_name,
419 )
421 def validate_json( 1amnbcdeopfghsiqrjkl
422 self,
423 data: str | bytes | bytearray,
424 /,
425 *,
426 strict: bool | None = None,
427 extra: ExtraValues | None = None,
428 context: Any | None = None,
429 experimental_allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
430 by_alias: bool | None = None,
431 by_name: bool | None = None,
432 ) -> T:
433 """!!! abstract "Usage Documentation"
434 [JSON Parsing](../concepts/json.md#json-parsing)
436 Validate a JSON string or bytes against the model.
438 JSON validated this way often comes from an external source, where a
439 [`ValidationError`][pydantic_core.ValidationError] can be the first sign that the source changed
440 shape. [Logfire](../integrations/logfire.md) retains the complete document and trace context
441 alongside the errors — see [Troubleshooting validation errors](../errors/troubleshooting.md).
443 Args:
444 data: The JSON data to validate against the model.
445 strict: Whether to strictly check types.
446 extra: Whether to ignore, allow, or forbid extra data during model validation.
447 See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
448 context: Additional context to use during validation.
449 experimental_allow_partial: **Experimental** whether to enable
450 [partial validation](../concepts/experimental.md#partial-validation), e.g. to process streams.
451 * False / 'off': Default behavior, no partial validation.
452 * True / 'on': Enable partial validation.
453 * 'trailing-strings': Enable partial validation and allow trailing strings in the input.
454 by_alias: Whether to use the field's alias when validating against the provided input data.
455 by_name: Whether to use the field's name when validating against the provided input data.
457 Returns:
458 The validated object.
459 """
460 if by_alias is False and by_name is not True: 1amnbcdeopfghiqrjkl
461 raise PydanticUserError( 1amnbcdeopfghiqrjkl
462 'At least one of `by_alias` or `by_name` must be set to True.',
463 code='validate-by-alias-and-name-false',
464 )
466 return self.validator.validate_json( 1amnbcdeopfghiqrjkl
467 data,
468 strict=strict,
469 extra=extra,
470 context=context,
471 allow_partial=experimental_allow_partial,
472 by_alias=by_alias,
473 by_name=by_name,
474 )
476 def validate_strings( 1amnbcdeopfghsiqrjkl
477 self,
478 obj: Any,
479 /,
480 *,
481 strict: bool | None = None,
482 extra: ExtraValues | None = None,
483 context: Any | None = None,
484 experimental_allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
485 by_alias: bool | None = None,
486 by_name: bool | None = None,
487 ) -> T:
488 """Validate object contains string data against the model.
490 Args:
491 obj: The object contains string data to validate.
492 strict: Whether to strictly check types.
493 extra: Whether to ignore, allow, or forbid extra data during model validation.
494 See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
495 context: Additional context to use during validation.
496 experimental_allow_partial: **Experimental** whether to enable
497 [partial validation](../concepts/experimental.md#partial-validation), e.g. to process streams.
498 * False / 'off': Default behavior, no partial validation.
499 * True / 'on': Enable partial validation.
500 * 'trailing-strings': Enable partial validation and allow trailing strings in the input.
501 by_alias: Whether to use the field's alias when validating against the provided input data.
502 by_name: Whether to use the field's name when validating against the provided input data.
504 Returns:
505 The validated object.
506 """
507 if by_alias is False and by_name is not True: 1amnbcdeopfghiqrjkl
508 raise PydanticUserError( 1amnbcdeopfghiqrjkl
509 'At least one of `by_alias` or `by_name` must be set to True.',
510 code='validate-by-alias-and-name-false',
511 )
513 return self.validator.validate_strings( 1amnbcdeopfghiqrjkl
514 obj,
515 strict=strict,
516 extra=extra,
517 context=context,
518 allow_partial=experimental_allow_partial,
519 by_alias=by_alias,
520 by_name=by_name,
521 )
523 def get_default_value(self, *, strict: bool | None = None, context: Any | None = None) -> Some[T] | None: 1amnbcdeopfghsiqrjkl
524 """Get the default value for the wrapped type.
526 Args:
527 strict: Whether to strictly check types.
528 context: Additional context to pass to the validator.
530 Returns:
531 The default value wrapped in a `Some` if there is one or None if not.
532 """
533 return self.validator.get_default_value(strict=strict, context=context) 1amnbcdeopfghiqrjkl
535 def dump_python( 1amnbcdeopfghsiqrjkl
536 self,
537 instance: T,
538 /,
539 *,
540 mode: Literal['json', 'python'] = 'python',
541 include: IncEx | None = None,
542 exclude: IncEx | None = None,
543 by_alias: bool | None = None,
544 exclude_unset: bool = False,
545 exclude_defaults: bool = False,
546 exclude_none: bool = False,
547 exclude_computed_fields: bool = False,
548 round_trip: bool = False,
549 warnings: bool | Literal['none', 'warn', 'error'] = True,
550 fallback: Callable[[Any], Any] | None = None,
551 serialize_as_any: bool = False,
552 polymorphic_serialization: bool | None = None,
553 context: Any | None = None,
554 ) -> Any:
555 """Dump an instance of the adapted type to a Python object.
557 Args:
558 instance: The Python object to serialize.
559 mode: The output format.
560 include: Fields to include in the output.
561 exclude: Fields to exclude from the output.
562 by_alias: Whether to use alias names for field names.
563 exclude_unset: Whether to exclude unset fields.
564 exclude_defaults: Whether to exclude fields with default values.
565 exclude_none: Whether to exclude fields with a value of `None`.
566 exclude_computed_fields: Whether to exclude computed fields.
567 While this can be useful for round-tripping, it is usually recommended to use the dedicated
568 `round_trip` parameter instead.
569 round_trip: Whether to output the serialized data in a way that is compatible with deserialization.
570 warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
571 "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
572 fallback: A function to call when an unknown value is encountered. If not provided,
573 a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
574 serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
575 polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
576 context: Additional context to pass to the serializer.
578 Returns:
579 The serialized object.
580 """
581 return self.serializer.to_python( 1amnbcdeopfghiqrjkl
582 instance,
583 mode=mode,
584 by_alias=by_alias,
585 include=include,
586 exclude=exclude,
587 exclude_unset=exclude_unset,
588 exclude_defaults=exclude_defaults,
589 exclude_none=exclude_none,
590 exclude_computed_fields=exclude_computed_fields,
591 round_trip=round_trip,
592 warnings=warnings,
593 fallback=fallback,
594 serialize_as_any=serialize_as_any,
595 polymorphic_serialization=polymorphic_serialization,
596 context=context,
597 )
599 def dump_json( 1amnbcdeopfghsiqrjkl
600 self,
601 instance: T,
602 /,
603 *,
604 indent: int | None = None,
605 ensure_ascii: bool = False,
606 include: IncEx | None = None,
607 exclude: IncEx | None = None,
608 by_alias: bool | None = None,
609 exclude_unset: bool = False,
610 exclude_defaults: bool = False,
611 exclude_none: bool = False,
612 exclude_computed_fields: bool = False,
613 round_trip: bool = False,
614 warnings: bool | Literal['none', 'warn', 'error'] = True,
615 fallback: Callable[[Any], Any] | None = None,
616 serialize_as_any: bool = False,
617 polymorphic_serialization: bool | None = None,
618 context: Any | None = None,
619 ) -> bytes:
620 """!!! abstract "Usage Documentation"
621 [JSON Serialization](../concepts/json.md#json-serialization)
623 Serialize an instance of the adapted type to JSON.
625 Args:
626 instance: The Python object to serialize.
627 indent: Number of spaces for JSON indentation.
628 ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
629 If `False` (the default), these characters will be output as-is.
630 include: Fields to include in the output.
631 exclude: Fields to exclude from the output.
632 by_alias: Whether to use alias names for field names.
633 exclude_unset: Whether to exclude unset fields.
634 exclude_defaults: Whether to exclude fields with default values.
635 exclude_none: Whether to exclude fields with a value of `None`.
636 exclude_computed_fields: Whether to exclude computed fields.
637 While this can be useful for round-tripping, it is usually recommended to use the dedicated
638 `round_trip` parameter instead.
639 round_trip: Whether to output the serialized data in a way that is compatible with deserialization.
640 warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
641 "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
642 fallback: A function to call when an unknown value is encountered. If not provided,
643 a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
644 serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
645 polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
646 context: Additional context to pass to the serializer.
648 Returns:
649 The JSON representation of the given instance as bytes.
650 """
651 return self.serializer.to_json( 1amnbcdeopfghiqrjkl
652 instance,
653 indent=indent,
654 ensure_ascii=ensure_ascii,
655 include=include,
656 exclude=exclude,
657 by_alias=by_alias,
658 exclude_unset=exclude_unset,
659 exclude_defaults=exclude_defaults,
660 exclude_none=exclude_none,
661 exclude_computed_fields=exclude_computed_fields,
662 round_trip=round_trip,
663 warnings=warnings,
664 fallback=fallback,
665 serialize_as_any=serialize_as_any,
666 polymorphic_serialization=polymorphic_serialization,
667 context=context,
668 )
670 def json_schema( 1amnbcdeopfghsiqrjkl
671 self,
672 *,
673 by_alias: bool | None = None,
674 ref_template: str = DEFAULT_REF_TEMPLATE,
675 union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
676 schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
677 mode: JsonSchemaMode = 'validation',
678 ) -> dict[str, Any]:
679 """Generate a JSON schema for the adapted type.
681 Args:
682 by_alias: Whether to use field aliases as keys in the generated JSON Schema. If `None` (the default),
683 aliases are used unless disabled by the configuration (i.e. `validate_by_alias=False` for validation
684 schemas). An explicit value takes precedence over the configuration.
685 ref_template: The format string used for generating $ref strings.
686 union_format: The format to use when combining schemas from unions together. Can be one of:
688 - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
689 keyword to combine schemas (the default).
690 - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
691 keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
692 type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
693 `any_of`.
694 schema_generator: To override the logic used to generate the JSON schema, as a subclass of
695 `GenerateJsonSchema` with your desired modifications
696 mode: The mode in which to generate the schema.
698 Returns:
699 The JSON schema for the model as a dictionary.
700 """
701 schema_generator_instance = schema_generator( 1amnbcdeopfghiqrjkl
702 by_alias=by_alias, ref_template=ref_template, union_format=union_format
703 )
704 if isinstance(self.core_schema, _mock_val_ser.MockCoreSchema): 1amnbcdeopfghiqrjkl
705 self.core_schema.rebuild() 1amnbcdeopfghiqrjkl
706 assert not isinstance(self.core_schema, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it' 1amnbcdeopfghiqrjkl
707 # The configuration provided to the type adapter (if any) is not part of the core schema,
708 # so we need to explicitly make it available to the JSON Schema generator:
709 with schema_generator_instance._config_wrapper_stack.push(self._config): 1amnbcdeopfghiqrjkl
710 return schema_generator_instance.generate(self.core_schema, mode=mode) 1amnbcdeopfghiqrjkl
712 @staticmethod 1amnbcdeopfghsiqrjkl
713 def json_schemas( 1amnbcdeopfghsiqrjkl
714 inputs: Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, TypeAdapter[Any]]],
715 /,
716 *,
717 by_alias: bool | None = None,
718 title: str | None = None,
719 description: str | None = None,
720 ref_template: str = DEFAULT_REF_TEMPLATE,
721 union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
722 schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
723 ) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]:
724 """Generate a JSON schema including definitions from multiple type adapters.
726 Args:
727 inputs: Inputs to schema generation. The first two items will form the keys of the (first)
728 output mapping; the type adapters will provide the core schemas that get converted into
729 definitions in the output JSON schema.
730 by_alias: Whether to use field aliases as keys in the generated JSON Schema. If `None` (the default),
731 aliases are used unless disabled by the configuration (i.e. `validate_by_alias=False` for validation
732 schemas). An explicit value takes precedence over the configuration.
733 title: The title for the schema.
734 description: The description for the schema.
735 ref_template: The format string used for generating $ref strings.
736 union_format: The format to use when combining schemas from unions together. Can be one of:
738 - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
739 keyword to combine schemas (the default).
740 - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
741 keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
742 type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
743 `any_of`.
744 schema_generator: The generator class used for creating the schema.
746 Returns:
747 A tuple where:
749 - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
750 whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
751 JsonRef references to definitions that are defined in the second returned element.)
752 - The second element is a JSON schema containing all definitions referenced in the first returned
753 element, along with the optional title and description keys.
755 """
756 schema_generator_instance = schema_generator( 1amnbcdeopfghiqrjkl
757 by_alias=by_alias, ref_template=ref_template, union_format=union_format
758 )
760 inputs_ = [] 1amnbcdeopfghiqrjkl
761 for key, mode, adapter in inputs: 1amnbcdeopfghiqrjkl
762 # This is the same pattern we follow for model json schemas - we attempt a core schema rebuild if we detect a mock
763 if isinstance(adapter.core_schema, _mock_val_ser.MockCoreSchema): 1amnbcdeopfghiqrjkl
764 adapter.core_schema.rebuild() 1amnbcdeopfghiqrjkl
765 assert not isinstance(adapter.core_schema, _mock_val_ser.MockCoreSchema), ( 1amnbcdeopfghiqrjkl
766 'this is a bug! please report it'
767 )
768 inputs_.append((key, mode, adapter.core_schema)) 1amnbcdeopfghiqrjkl
770 json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_) 1amnbcdeopfghiqrjkl
772 json_schema: dict[str, Any] = {} 1amnbcdeopfghiqrjkl
773 if definitions: 1amnbcdeopfghiqrjkl
774 json_schema['$defs'] = definitions 1amnbcdeopfghiqrjkl
775 if title: 1amnbcdeopfghiqrjkl
776 json_schema['title'] = title 1amnbcdeopfghiqrjkl
777 if description: 1amnbcdeopfghiqrjkl
778 json_schema['description'] = description 1amnbcdeopfghiqrjkl
780 return json_schemas_map, json_schema 1amnbcdeopfghiqrjkl