pboot-validator 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. pboot_validator/__init__.py +461 -0
  2. pboot_validator/_internal/__init__.py +0 -0
  3. pboot_validator/_internal/_config.py +408 -0
  4. pboot_validator/_internal/_contextlib.py +84 -0
  5. pboot_validator/_internal/_core_metadata.py +97 -0
  6. pboot_validator/_internal/_core_utils.py +156 -0
  7. pboot_validator/_internal/_dataclasses.py +327 -0
  8. pboot_validator/_internal/_decorators.py +906 -0
  9. pboot_validator/_internal/_decorators_v1.py +174 -0
  10. pboot_validator/_internal/_discriminated_union.py +510 -0
  11. pboot_validator/_internal/_docs_extraction.py +128 -0
  12. pboot_validator/_internal/_fields.py +910 -0
  13. pboot_validator/_internal/_forward_ref.py +23 -0
  14. pboot_validator/_internal/_generate_schema.py +3053 -0
  15. pboot_validator/_internal/_generics.py +572 -0
  16. pboot_validator/_internal/_git.py +27 -0
  17. pboot_validator/_internal/_import_utils.py +20 -0
  18. pboot_validator/_internal/_known_annotated_metadata.py +412 -0
  19. pboot_validator/_internal/_mock_val_ser.py +241 -0
  20. pboot_validator/_internal/_model_construction.py +833 -0
  21. pboot_validator/_internal/_namespace_utils.py +300 -0
  22. pboot_validator/_internal/_repr.py +129 -0
  23. pboot_validator/_internal/_schema_gather.py +49 -0
  24. pboot_validator/_internal/_schema_generation_shared.py +126 -0
  25. pboot_validator/_internal/_serializers.py +59 -0
  26. pboot_validator/_internal/_signature.py +193 -0
  27. pboot_validator/_internal/_type_refs.py +128 -0
  28. pboot_validator/_internal/_typing_extra.py +506 -0
  29. pboot_validator/_internal/_utils.py +433 -0
  30. pboot_validator/_internal/_validate_call.py +141 -0
  31. pboot_validator/_internal/_validators.py +541 -0
  32. pboot_validator/_migration.py +317 -0
  33. pboot_validator/alias_generators.py +62 -0
  34. pboot_validator/aliases.py +136 -0
  35. pboot_validator/annotated_handlers.py +123 -0
  36. pboot_validator/class_validators.py +5 -0
  37. pboot_validator/color.py +605 -0
  38. pboot_validator/config.py +1295 -0
  39. pboot_validator/dataclasses.py +385 -0
  40. pboot_validator/datetime_parse.py +5 -0
  41. pboot_validator/decorator.py +5 -0
  42. pboot_validator/deprecated/__init__.py +0 -0
  43. pboot_validator/deprecated/class_validators.py +257 -0
  44. pboot_validator/deprecated/config.py +72 -0
  45. pboot_validator/deprecated/copy_internals.py +224 -0
  46. pboot_validator/deprecated/decorator.py +286 -0
  47. pboot_validator/deprecated/json.py +142 -0
  48. pboot_validator/deprecated/parse.py +81 -0
  49. pboot_validator/deprecated/tools.py +104 -0
  50. pboot_validator/env_settings.py +5 -0
  51. pboot_validator/error_wrappers.py +5 -0
  52. pboot_validator/errors.py +185 -0
  53. pboot_validator/experimental/__init__.py +1 -0
  54. pboot_validator/experimental/arguments_schema.py +44 -0
  55. pboot_validator/experimental/missing_sentinel.py +29 -0
  56. pboot_validator/experimental/pipeline.py +684 -0
  57. pboot_validator/fields.py +2065 -0
  58. pboot_validator/functional_serializers.py +461 -0
  59. pboot_validator/functional_validators.py +920 -0
  60. pboot_validator/generics.py +5 -0
  61. pboot_validator/json.py +5 -0
  62. pboot_validator/json_schema.py +3283 -0
  63. pboot_validator/main.py +1947 -0
  64. pboot_validator/mypy.py +1469 -0
  65. pboot_validator/networks.py +1417 -0
  66. pboot_validator/parse.py +5 -0
  67. pboot_validator/plugin/__init__.py +190 -0
  68. pboot_validator/plugin/_loader.py +56 -0
  69. pboot_validator/plugin/_schema_validator.py +152 -0
  70. pboot_validator/py.typed +0 -0
  71. pboot_validator/root_model.py +189 -0
  72. pboot_validator/schema.py +5 -0
  73. pboot_validator/tools.py +5 -0
  74. pboot_validator/type_adapter.py +780 -0
  75. pboot_validator/types.py +3405 -0
  76. pboot_validator/typing.py +5 -0
  77. pboot_validator/utils.py +5 -0
  78. pboot_validator/v1/__init__.py +131 -0
  79. pboot_validator/v1/_hypothesis_plugin.py +391 -0
  80. pboot_validator/v1/annotated_types.py +72 -0
  81. pboot_validator/v1/class_validators.py +361 -0
  82. pboot_validator/v1/color.py +494 -0
  83. pboot_validator/v1/config.py +191 -0
  84. pboot_validator/v1/dataclasses.py +503 -0
  85. pboot_validator/v1/datetime_parse.py +248 -0
  86. pboot_validator/v1/decorator.py +264 -0
  87. pboot_validator/v1/env_settings.py +350 -0
  88. pboot_validator/v1/error_wrappers.py +161 -0
  89. pboot_validator/v1/errors.py +646 -0
  90. pboot_validator/v1/fields.py +1253 -0
  91. pboot_validator/v1/generics.py +400 -0
  92. pboot_validator/v1/json.py +112 -0
  93. pboot_validator/v1/main.py +1130 -0
  94. pboot_validator/v1/mypy.py +950 -0
  95. pboot_validator/v1/networks.py +747 -0
  96. pboot_validator/v1/parse.py +66 -0
  97. pboot_validator/v1/py.typed +0 -0
  98. pboot_validator/v1/schema.py +1163 -0
  99. pboot_validator/v1/tools.py +92 -0
  100. pboot_validator/v1/types.py +1213 -0
  101. pboot_validator/v1/typing.py +627 -0
  102. pboot_validator/v1/utils.py +807 -0
  103. pboot_validator/v1/validators.py +768 -0
  104. pboot_validator/v1/version.py +38 -0
  105. pboot_validator/validate_call_decorator.py +121 -0
  106. pboot_validator/validators.py +5 -0
  107. pboot_validator/version.py +113 -0
  108. pboot_validator/warnings.py +130 -0
  109. pboot_validator-1.0.0.dist-info/METADATA +93 -0
  110. pboot_validator-1.0.0.dist-info/RECORD +112 -0
  111. pboot_validator-1.0.0.dist-info/WHEEL +4 -0
  112. pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,780 @@
1
+ """Type adapter specification."""
2
+
3
+ from __future__ import annotations as _annotations
4
+
5
+ import sys
6
+ import types
7
+ from collections.abc import Callable, Iterable
8
+ from dataclasses import is_dataclass
9
+ from types import FrameType
10
+ from typing import (
11
+ Any,
12
+ Generic,
13
+ Literal,
14
+ TypeVar,
15
+ cast,
16
+ final,
17
+ )
18
+
19
+ from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator, Some
20
+ from typing_extensions import ParamSpec, TypeForm, is_typeddict
21
+
22
+ from pboot_validator.errors import PydanticUserError
23
+ from pboot_validator.main import BaseModel, IncEx
24
+
25
+ from ._internal import _config, _generate_schema, _mock_val_ser, _namespace_utils, _repr, _typing_extra, _utils
26
+ from .config import ConfigDict, ExtraValues
27
+ from .errors import PydanticUndefinedAnnotation
28
+ from .json_schema import (
29
+ DEFAULT_REF_TEMPLATE,
30
+ GenerateJsonSchema,
31
+ JsonSchemaKeyT,
32
+ JsonSchemaMode,
33
+ JsonSchemaValue,
34
+ )
35
+ from .plugin._schema_validator import PluggableSchemaValidator, create_schema_validator
36
+
37
+ T = TypeVar('T')
38
+ R = TypeVar('R')
39
+ P = ParamSpec('P')
40
+ TypeAdapterT = TypeVar('TypeAdapterT', bound='TypeAdapter')
41
+
42
+
43
+ def _getattr_no_parents(obj: Any, attribute: str) -> Any:
44
+ """Returns the attribute value without attempting to look up attributes from parent types."""
45
+ if hasattr(obj, '__dict__'):
46
+ try:
47
+ return obj.__dict__[attribute]
48
+ except KeyError:
49
+ pass
50
+
51
+ slots = getattr(obj, '__slots__', None)
52
+ if slots is not None and attribute in slots:
53
+ return getattr(obj, attribute)
54
+ else:
55
+ raise AttributeError(attribute)
56
+
57
+
58
+ def _type_has_config(type_: Any) -> bool:
59
+ """Returns whether the type has config."""
60
+ type_ = _typing_extra.annotated_type(type_) or type_
61
+ try:
62
+ return issubclass(type_, BaseModel) or is_dataclass(type_) or is_typeddict(type_)
63
+ except TypeError:
64
+ # type is not a class
65
+ return False
66
+
67
+
68
+ @final
69
+ class TypeAdapter(Generic[T]):
70
+ """!!! abstract "Usage Documentation"
71
+ [`TypeAdapter`](../concepts/type_adapter.md)
72
+
73
+ Type adapters provide a flexible way to perform validation and serialization based on a Python type.
74
+
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).
77
+
78
+ **Note:** `TypeAdapter` instances are not types, and cannot be used as type annotations for fields.
79
+
80
+ Args:
81
+ type: The type associated with the `TypeAdapter`.
82
+ config: Configuration for the `TypeAdapter`, should be a dictionary conforming to
83
+ [`ConfigDict`][pboot_validator.config.ConfigDict].
84
+
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.
93
+
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.
100
+
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.
106
+
107
+ ??? info "Namespace management nuances and implementation details"
108
+
109
+ Here, we collect some notes on namespace management, and subtle differences from `BaseModel`:
110
+
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.
116
+
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.
120
+
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.
124
+
125
+ For example, take the following:
126
+
127
+ ```python {title="a.py"}
128
+ IntList = list[int]
129
+ OuterDict = dict[str, 'IntList']
130
+ ```
131
+
132
+ ```python {test="skip" title="b.py"}
133
+ from a import OuterDict
134
+
135
+ from pboot_validator import TypeAdapter
136
+
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
+ ```
141
+
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.
145
+
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.
151
+
152
+ But at the very least this behavior is _subtly_ different from `BaseModel`'s.
153
+ """
154
+
155
+ core_schema: CoreSchema
156
+ validator: SchemaValidator | PluggableSchemaValidator
157
+ serializer: SchemaSerializer
158
+ pydantic_complete: bool
159
+
160
+ def __init__(
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:
169
+ raise PydanticUserError(
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
+ )
176
+
177
+ self._type = type
178
+ self._config = config
179
+ self._parent_depth = _parent_depth
180
+ self.pydantic_complete = False
181
+
182
+ parent_frame = self._fetch_parent_frame()
183
+ if isinstance(type, types.FunctionType):
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:
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
190
+ else: # pragma: no cover
191
+ parent_ns = None
192
+ globalns, localns = _namespace_utils.ns_for_function(
193
+ type,
194
+ parent_namespace=parent_ns,
195
+ )
196
+ parent_namespace = None
197
+ else:
198
+ if parent_frame is not None:
199
+ globalns = parent_frame.f_globals
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 {}
202
+ else: # pragma: no cover
203
+ globalns = {}
204
+ localns = {}
205
+ parent_namespace = localns
206
+
207
+ self._module_name = module or cast(str, globalns.get('__name__', ''))
208
+ self._init_core_attrs(
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
+ )
215
+
216
+ def _fetch_parent_frame(self) -> FrameType | None:
217
+ frame = sys._getframe(self._parent_depth)
218
+ if frame.f_globals.get('__name__') == 'typing':
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
224
+
225
+ return frame
226
+
227
+ def _init_core_attrs(
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.
231
+
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.
237
+
238
+ Returns:
239
+ `True` if the core schema, validator, and serializer were successfully initialized, otherwise `False`.
240
+
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:
246
+ _mock_val_ser.set_type_adapter_mocks(self)
247
+ self.pydantic_complete = False
248
+ return False
249
+
250
+ try:
251
+ self.core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__')
252
+ self.validator = _getattr_no_parents(self._type, '__pydantic_validator__')
253
+ self.serializer = _getattr_no_parents(self._type, '__pydantic_serializer__')
254
+
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 (
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()
264
+ except AttributeError:
265
+ config_wrapper = _config.ConfigWrapper(self._config)
266
+
267
+ schema_generator = _generate_schema.GenerateSchema(config_wrapper, ns_resolver=ns_resolver)
268
+
269
+ try:
270
+ core_schema = schema_generator.generate_schema(self._type)
271
+ except PydanticUndefinedAnnotation:
272
+ if raise_errors:
273
+ raise
274
+ _mock_val_ser.set_type_adapter_mocks(self)
275
+ return False
276
+
277
+ try:
278
+ self.core_schema = schema_generator.clean_schema(core_schema)
279
+ except _generate_schema.InvalidSchemaError:
280
+ _mock_val_ser.set_type_adapter_mocks(self)
281
+ return False
282
+
283
+ core_config = config_wrapper.core_config(None)
284
+
285
+ self.validator = create_schema_validator(
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)
295
+
296
+ self.pydantic_complete = True
297
+ return True
298
+
299
+ @property
300
+ def _defer_build(self) -> bool:
301
+ config = self._config if self._config is not None else self._model_config
302
+ if config:
303
+ return config.get('defer_build') is True
304
+ return False
305
+
306
+ @property
307
+ def _model_config(self) -> ConfigDict | None:
308
+ type_: Any = _typing_extra.annotated_type(self._type) or self._type # Eg FastAPI heavily uses Annotated
309
+ if _utils.lenient_issubclass(type_, BaseModel):
310
+ return type_.model_config
311
+ return getattr(type_, '__pydantic_config__', None)
312
+
313
+ def __repr__(self) -> str:
314
+ return f'TypeAdapter({_repr.display_as_type(self._type)})'
315
+
316
+ def rebuild(
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.
325
+
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.
328
+
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`.
338
+
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:
344
+ return None
345
+
346
+ if _types_namespace is not None:
347
+ rebuild_ns = _types_namespace
348
+ elif _parent_namespace_depth > 0:
349
+ rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
350
+ else:
351
+ rebuild_ns = {}
352
+
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
356
+ ns_resolver = _namespace_utils.NsResolver(
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)
361
+
362
+ def validate_python(
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.
376
+
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)).
381
+
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][pboot_validator.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.
396
+
397
+ !!! note
398
+ When using `TypeAdapter` with a Pydantic `dataclass`, the use of the `from_attributes`
399
+ argument is not supported.
400
+
401
+ Returns:
402
+ The validated object.
403
+ """
404
+ if by_alias is False and by_name is not True:
405
+ raise PydanticUserError(
406
+ 'At least one of `by_alias` or `by_name` must be set to True.',
407
+ code='validate-by-alias-and-name-false',
408
+ )
409
+
410
+ return self.validator.validate_python(
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
+ )
420
+
421
+ def validate_json(
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)
435
+
436
+ Validate a JSON string or bytes against the model.
437
+
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).
442
+
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][pboot_validator.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.
456
+
457
+ Returns:
458
+ The validated object.
459
+ """
460
+ if by_alias is False and by_name is not True:
461
+ raise PydanticUserError(
462
+ 'At least one of `by_alias` or `by_name` must be set to True.',
463
+ code='validate-by-alias-and-name-false',
464
+ )
465
+
466
+ return self.validator.validate_json(
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
+ )
475
+
476
+ def validate_strings(
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.
489
+
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][pboot_validator.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.
503
+
504
+ Returns:
505
+ The validated object.
506
+ """
507
+ if by_alias is False and by_name is not True:
508
+ raise PydanticUserError(
509
+ 'At least one of `by_alias` or `by_name` must be set to True.',
510
+ code='validate-by-alias-and-name-false',
511
+ )
512
+
513
+ return self.validator.validate_strings(
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
+ )
522
+
523
+ def get_default_value(self, *, strict: bool | None = None, context: Any | None = None) -> Some[T] | None:
524
+ """Get the default value for the wrapped type.
525
+
526
+ Args:
527
+ strict: Whether to strictly check types.
528
+ context: Additional context to pass to the validator.
529
+
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)
534
+
535
+ def dump_python(
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.
556
+
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 None values.
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.
577
+
578
+ Returns:
579
+ The serialized object.
580
+ """
581
+ return self.serializer.to_python(
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
+ )
598
+
599
+ def dump_json(
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)
622
+
623
+ Serialize an instance of the adapted type to JSON.
624
+
625
+ Args:
626
+ instance: The instance to be serialized.
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.
631
+ exclude: Fields to exclude.
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 serialize and deserialize the instance to ensure round-tripping.
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.
647
+
648
+ Returns:
649
+ The JSON representation of the given instance as bytes.
650
+ """
651
+ return self.serializer.to_json(
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
+ )
669
+
670
+ def json_schema(
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.
680
+
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:
687
+
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.
697
+
698
+ Returns:
699
+ The JSON schema for the model as a dictionary.
700
+ """
701
+ schema_generator_instance = schema_generator(
702
+ by_alias=by_alias, ref_template=ref_template, union_format=union_format
703
+ )
704
+ if isinstance(self.core_schema, _mock_val_ser.MockCoreSchema):
705
+ self.core_schema.rebuild()
706
+ assert not isinstance(self.core_schema, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it'
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):
710
+ return schema_generator_instance.generate(self.core_schema, mode=mode)
711
+
712
+ @staticmethod
713
+ def json_schemas(
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.
725
+
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:
737
+
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.
745
+
746
+ Returns:
747
+ A tuple where:
748
+
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.
754
+
755
+ """
756
+ schema_generator_instance = schema_generator(
757
+ by_alias=by_alias, ref_template=ref_template, union_format=union_format
758
+ )
759
+
760
+ inputs_ = []
761
+ for key, mode, adapter in inputs:
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):
764
+ adapter.core_schema.rebuild()
765
+ assert not isinstance(adapter.core_schema, _mock_val_ser.MockCoreSchema), (
766
+ 'this is a bug! please report it'
767
+ )
768
+ inputs_.append((key, mode, adapter.core_schema))
769
+
770
+ json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_)
771
+
772
+ json_schema: dict[str, Any] = {}
773
+ if definitions:
774
+ json_schema['$defs'] = definitions
775
+ if title:
776
+ json_schema['title'] = title
777
+ if description:
778
+ json_schema['description'] = description
779
+
780
+ return json_schemas_map, json_schema