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,412 @@
1
+ from __future__ import annotations
2
+
3
+ from collections import defaultdict
4
+ from collections.abc import Iterable
5
+ from copy import copy
6
+ from functools import lru_cache, partial
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from pydantic_core import CoreSchema, PydanticCustomError, ValidationError, to_jsonable_python
10
+ from pydantic_core import core_schema as cs
11
+
12
+ from ._fields import PydanticMetadata
13
+ from ._import_utils import import_cached_field_info
14
+
15
+ if TYPE_CHECKING:
16
+ pass
17
+
18
+ STRICT = {'strict'}
19
+ FAIL_FAST = {'fail_fast'}
20
+ LENGTH_CONSTRAINTS = {'min_length', 'max_length'}
21
+ INEQUALITY = {'le', 'ge', 'lt', 'gt'}
22
+ NUMERIC_CONSTRAINTS = {'multiple_of', *INEQUALITY}
23
+ ALLOW_INF_NAN = {'allow_inf_nan'}
24
+
25
+ STR_CONSTRAINTS = {
26
+ *LENGTH_CONSTRAINTS,
27
+ *STRICT,
28
+ 'strip_whitespace',
29
+ 'to_lower',
30
+ 'to_upper',
31
+ 'pattern',
32
+ 'coerce_numbers_to_str',
33
+ 'ascii_only',
34
+ }
35
+ BYTES_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
36
+
37
+ LIST_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
38
+ TUPLE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
39
+ SET_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
40
+ DICT_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
41
+ GENERATOR_CONSTRAINTS = LENGTH_CONSTRAINTS
42
+ SEQUENCE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *FAIL_FAST}
43
+
44
+ FLOAT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT}
45
+ DECIMAL_CONSTRAINTS = {'max_digits', 'decimal_places', *FLOAT_CONSTRAINTS}
46
+ FRACTION_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
47
+ INT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
48
+ BOOL_CONSTRAINTS = STRICT
49
+ UUID_CONSTRAINTS = STRICT
50
+
51
+ DATE_TIME_CONSTRAINTS = {*INEQUALITY, *STRICT}
52
+ TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
53
+ LAX_OR_STRICT_CONSTRAINTS = STRICT
54
+ ENUM_CONSTRAINTS = STRICT
55
+ COMPLEX_CONSTRAINTS = STRICT
56
+
57
+ UNION_CONSTRAINTS = {'union_mode'}
58
+ URL_CONSTRAINTS = {
59
+ 'max_length',
60
+ 'allowed_schemes',
61
+ 'host_required',
62
+ 'default_host',
63
+ 'default_port',
64
+ 'default_path',
65
+ *STRICT,
66
+ }
67
+
68
+ CONSTRAINTS_TO_ALLOWED_SCHEMAS: dict[str, set[str]] = defaultdict(set)
69
+
70
+ constraint_schema_pairings: list[tuple[set[str], tuple[str, ...]]] = [
71
+ (STR_CONSTRAINTS, ('str',)),
72
+ (BYTES_CONSTRAINTS, ('bytes',)),
73
+ (LIST_CONSTRAINTS, ('list', 'deque')),
74
+ (TUPLE_CONSTRAINTS, ('tuple',)),
75
+ (SET_CONSTRAINTS, ('set', 'frozenset')),
76
+ (DICT_CONSTRAINTS, ('dict', 'frozendict', 'ordered-dict', 'counter')),
77
+ (GENERATOR_CONSTRAINTS, ('generator',)),
78
+ (FLOAT_CONSTRAINTS, ('float',)),
79
+ (INT_CONSTRAINTS, ('int',)),
80
+ (DATE_TIME_CONSTRAINTS, ('date', 'time', 'datetime')),
81
+ (TIMEDELTA_CONSTRAINTS, ('timedelta',)),
82
+ (STRICT, ('typed-dict', 'model')),
83
+ (UNION_CONSTRAINTS, ('union',)),
84
+ (URL_CONSTRAINTS, ('url', 'multi-host-url')),
85
+ (BOOL_CONSTRAINTS, ('bool',)),
86
+ (UUID_CONSTRAINTS, ('uuid',)),
87
+ (LAX_OR_STRICT_CONSTRAINTS, ('lax-or-strict',)),
88
+ (ENUM_CONSTRAINTS, ('enum',)),
89
+ (DECIMAL_CONSTRAINTS, ('decimal',)),
90
+ (COMPLEX_CONSTRAINTS, ('complex',)),
91
+ (FRACTION_CONSTRAINTS, ('fraction',)),
92
+ ]
93
+
94
+ for constraints, schemas in constraint_schema_pairings:
95
+ for c in constraints:
96
+ CONSTRAINTS_TO_ALLOWED_SCHEMAS[c].update(schemas)
97
+
98
+
99
+ def as_jsonable_value(v: Any) -> Any:
100
+ if type(v) not in (int, str, float, bytes, bool, type(None)):
101
+ return to_jsonable_python(v)
102
+ return v
103
+
104
+
105
+ def _is_grouped_metadata(annotation: Any) -> bool:
106
+ """Check whether `annotation` is an instance of the `annotated_types.GroupedMetadata` protocol."""
107
+ # `annotated_types.GroupedMetadata` is a `@runtime_checkable` protocol, and `isinstance()` checks
108
+ # are quite slow. Instead, we check against the `__is_annotated_types_grouped_metadata__` property
109
+ # (see https://github.com/annotated-types/annotated-types/blob/96eef3cb/annotated_types/__init__.py#L169-L171).
110
+ # The `is True` check excludes classes (for which the property object itself is returned):
111
+ return getattr(annotation, '__is_annotated_types_grouped_metadata__', False) is True
112
+
113
+
114
+ def expand_grouped_metadata(annotations: Iterable[Any]) -> Iterable[Any]:
115
+ """Expand the annotations.
116
+
117
+ Args:
118
+ annotations: An iterable of annotations.
119
+
120
+ Returns:
121
+ An iterable of expanded annotations.
122
+
123
+ Example:
124
+ ```python
125
+ from annotated_types import Ge, Len
126
+
127
+ from pboot_validator._internal._known_annotated_metadata import expand_grouped_metadata
128
+
129
+ print(list(expand_grouped_metadata([Ge(4), Len(5)])))
130
+ #> [Ge(ge=4), MinLen(min_length=5)]
131
+ ```
132
+ """
133
+ FieldInfo = import_cached_field_info()
134
+
135
+ for annotation in annotations:
136
+ if _is_grouped_metadata(annotation):
137
+ yield from annotation
138
+ elif isinstance(annotation, FieldInfo):
139
+ yield from annotation.metadata
140
+ # this is a bit problematic in that it results in duplicate metadata
141
+ # all of our "consumers" can handle it, but it is not ideal
142
+ # we probably should split up FieldInfo into:
143
+ # - annotated types metadata
144
+ # - individual metadata known only to Pydantic
145
+ annotation = copy(annotation)
146
+ annotation.metadata = []
147
+ yield annotation
148
+ else:
149
+ yield annotation
150
+
151
+
152
+ @lru_cache
153
+ def _get_at_to_constraint_map() -> dict[type, str]:
154
+ """Return a mapping of annotated types to constraints.
155
+
156
+ Normally, we would define a mapping like this in the module scope, but we can't do that
157
+ because we don't permit module level imports of `annotated_types`, in an attempt to speed up
158
+ the import time of `pydantic`. We still only want to have this dictionary defined in one place,
159
+ so we use this function to cache the result.
160
+ """
161
+ import annotated_types as at
162
+
163
+ return {
164
+ at.Gt: 'gt',
165
+ at.Ge: 'ge',
166
+ at.Lt: 'lt',
167
+ at.Le: 'le',
168
+ at.MultipleOf: 'multiple_of',
169
+ at.MinLen: 'min_length',
170
+ at.MaxLen: 'max_length',
171
+ }
172
+
173
+
174
+ def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | None: # noqa: C901
175
+ """Apply `annotation` to `schema` if it is an annotation we know about (Gt, Le, etc.).
176
+ Otherwise return `None`.
177
+
178
+ This does not handle all known annotations. If / when it does, it can always
179
+ return a CoreSchema and return the unmodified schema if the annotation should be ignored.
180
+
181
+ Assumes that GroupedMetadata has already been expanded via `expand_grouped_metadata`.
182
+
183
+ Args:
184
+ annotation: The annotation.
185
+ schema: The schema.
186
+
187
+ Returns:
188
+ An updated schema with annotation if it is an annotation we know about, `None` otherwise.
189
+
190
+ Raises:
191
+ RuntimeError: If a constraint can't be applied to a specific schema type.
192
+ ValueError: If an unknown constraint is encountered.
193
+ """
194
+ import annotated_types as at
195
+
196
+ from ._validators import NUMERIC_VALIDATOR_LOOKUP, forbid_inf_nan_check
197
+
198
+ schema = schema.copy()
199
+ schema_update, other_metadata = collect_known_metadata([annotation])
200
+ schema_type = schema['type']
201
+
202
+ chain_schema_constraints: set[str] = {
203
+ 'pattern',
204
+ 'strip_whitespace',
205
+ 'to_lower',
206
+ 'to_upper',
207
+ 'coerce_numbers_to_str',
208
+ 'ascii_only',
209
+ }
210
+ chain_schema_steps: list[CoreSchema] = []
211
+
212
+ for constraint, value in schema_update.items():
213
+ if constraint not in CONSTRAINTS_TO_ALLOWED_SCHEMAS:
214
+ raise ValueError(f'Unknown constraint {constraint}')
215
+ allowed_schemas = CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint]
216
+
217
+ # if it becomes necessary to handle more than one constraint
218
+ # in this recursive case with function-after or function-wrap, we should refactor
219
+ # this is a bit challenging because we sometimes want to apply constraints to the inner schema,
220
+ # whereas other times we want to wrap the existing schema with a new one that enforces a new constraint.
221
+ if schema_type in {'function-before', 'function-wrap', 'function-after'} and constraint == 'strict':
222
+ schema['schema'] = apply_known_metadata(annotation, schema['schema']) # type: ignore # schema is function schema
223
+ return schema
224
+
225
+ # if we're allowed to apply constraint directly to the schema, like le to int, do that
226
+ if schema_type in allowed_schemas:
227
+ if constraint == 'union_mode' and schema_type == 'union':
228
+ schema['mode'] = value # type: ignore # schema is UnionSchema
229
+ else:
230
+ schema[constraint] = value
231
+ continue
232
+
233
+ # else, apply a function after validator to the schema to enforce the corresponding constraint
234
+ if constraint in chain_schema_constraints:
235
+
236
+ def _apply_constraint_with_incompatibility_info(
237
+ value: Any, handler: cs.ValidatorFunctionWrapHandler
238
+ ) -> Any:
239
+ try:
240
+ x = handler(value)
241
+ except ValidationError as ve:
242
+ # if the error is about the type, it's likely that the constraint is incompatible the type of the field
243
+ # for example, the following invalid schema wouldn't be caught during schema build, but rather at this point
244
+ # with a cryptic 'string_type' error coming from the string validator,
245
+ # that we'd rather express as a constraint incompatibility error (TypeError)
246
+ # Annotated[list[int], Field(pattern='abc')]
247
+ if 'type' in ve.errors()[0]['type']:
248
+ raise TypeError(
249
+ f"Unable to apply constraint '{constraint}' to supplied value {value} for schema of type '{schema_type}'" # noqa: B023
250
+ )
251
+ raise ve
252
+ return x
253
+
254
+ chain_schema_steps.append(
255
+ cs.no_info_wrap_validator_function(
256
+ _apply_constraint_with_incompatibility_info, cs.str_schema(**{constraint: value})
257
+ )
258
+ )
259
+ elif constraint in NUMERIC_VALIDATOR_LOOKUP:
260
+ if constraint in LENGTH_CONSTRAINTS:
261
+ inner_schema = schema
262
+ while inner_schema['type'] in {'function-before', 'function-wrap', 'function-after'}:
263
+ inner_schema = inner_schema['schema'] # type: ignore
264
+ inner_schema_type = inner_schema['type']
265
+ if inner_schema_type == 'list' or (
266
+ inner_schema_type == 'json-or-python' and inner_schema['json_schema']['type'] == 'list' # type: ignore
267
+ ):
268
+ js_constraint_key = 'minItems' if constraint == 'min_length' else 'maxItems'
269
+ else:
270
+ js_constraint_key = 'minLength' if constraint == 'min_length' else 'maxLength'
271
+ else:
272
+ js_constraint_key = constraint
273
+
274
+ validator_kwargs = {constraint: value}
275
+ if constraint == 'decimal_places' and schema_update.get('max_digits') is not None:
276
+ # The whole digits limit depends on both constraints, and is checked alongside `decimal_places`:
277
+ validator_kwargs['max_digits'] = schema_update['max_digits']
278
+ schema = cs.no_info_after_validator_function(
279
+ partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **validator_kwargs), schema
280
+ )
281
+ metadata = schema.get('metadata', {})
282
+ if (existing_json_schema_updates := metadata.get('pydantic_js_updates')) is not None:
283
+ metadata['pydantic_js_updates'] = {
284
+ **existing_json_schema_updates,
285
+ **{js_constraint_key: as_jsonable_value(value)},
286
+ }
287
+ else:
288
+ metadata['pydantic_js_updates'] = {js_constraint_key: as_jsonable_value(value)}
289
+ schema['metadata'] = metadata
290
+ elif constraint == 'allow_inf_nan' and value is False:
291
+ schema = cs.no_info_after_validator_function(
292
+ forbid_inf_nan_check,
293
+ schema,
294
+ )
295
+ else:
296
+ # It's rare that we'd get here, but it's possible if we add a new constraint and forget to handle it
297
+ # Most constraint errors are caught at runtime during attempted application
298
+ raise RuntimeError(f"Unable to apply constraint '{constraint}' to schema of type '{schema_type}'")
299
+
300
+ for annotation in other_metadata:
301
+ if (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()):
302
+ constraint = at_to_constraint_map[annotation_type]
303
+ validator = NUMERIC_VALIDATOR_LOOKUP.get(constraint)
304
+ if validator is None:
305
+ raise ValueError(f'Unknown constraint {constraint}')
306
+ schema = cs.no_info_after_validator_function(
307
+ partial(validator, {constraint: getattr(annotation, constraint)}), schema
308
+ )
309
+ continue
310
+ elif isinstance(annotation, (at.Predicate, at.Not)):
311
+ predicate_name = f'{annotation.func.__qualname__!r} ' if hasattr(annotation.func, '__qualname__') else ''
312
+
313
+ # Note: B023 is ignored because even though we iterate over `other_metadata`, it is guaranteed
314
+ # to be of length 1. `apply_known_metadata()` is called from `GenerateSchema`, where annotations
315
+ # were already expanded via `expand_grouped_metadata()`. Confusing, but this falls into the annotations
316
+ # refactor.
317
+ if isinstance(annotation, at.Predicate):
318
+
319
+ def val_func(v: Any) -> Any:
320
+ predicate_satisfied = annotation.func(v) # noqa: B023
321
+ if not predicate_satisfied:
322
+ raise PydanticCustomError(
323
+ 'predicate_failed',
324
+ f'Predicate {predicate_name}failed', # pyright: ignore[reportArgumentType] # noqa: B023
325
+ )
326
+ return v
327
+
328
+ else:
329
+
330
+ def val_func(v: Any) -> Any:
331
+ predicate_satisfied = annotation.func(v) # noqa: B023
332
+ if predicate_satisfied:
333
+ raise PydanticCustomError(
334
+ 'not_operation_failed',
335
+ f'Not of {predicate_name}failed', # pyright: ignore[reportArgumentType] # noqa: B023
336
+ )
337
+ return v
338
+
339
+ schema = cs.no_info_after_validator_function(val_func, schema)
340
+ else:
341
+ # ignore any other unknown metadata
342
+ return None
343
+
344
+ if chain_schema_steps:
345
+ chain_schema_steps = [schema] + chain_schema_steps
346
+ return cs.chain_schema(chain_schema_steps)
347
+
348
+ return schema
349
+
350
+
351
+ def collect_known_metadata(annotations: Iterable[Any]) -> tuple[dict[str, Any], list[Any]]:
352
+ """Split `annotations` into known metadata and unknown annotations.
353
+
354
+ Args:
355
+ annotations: An iterable of annotations.
356
+
357
+ Returns:
358
+ A tuple contains a dict of known metadata and a list of unknown annotations.
359
+
360
+ Example:
361
+ ```python
362
+ from annotated_types import Gt, Len
363
+
364
+ from pboot_validator._internal._known_annotated_metadata import collect_known_metadata
365
+
366
+ print(collect_known_metadata([Gt(1), Len(42), ...]))
367
+ #> ({'gt': 1, 'min_length': 42}, [Ellipsis])
368
+ ```
369
+ """
370
+ annotations = expand_grouped_metadata(annotations)
371
+
372
+ res: dict[str, Any] = {}
373
+ remaining: list[Any] = []
374
+
375
+ for annotation in annotations:
376
+ # isinstance(annotation, PydanticMetadata) also covers ._fields:_PydanticGeneralMetadata
377
+ if isinstance(annotation, PydanticMetadata):
378
+ res.update(annotation.__dict__)
379
+ # we don't use dataclasses.asdict because that recursively calls asdict on the field values
380
+ elif (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()):
381
+ constraint = at_to_constraint_map[annotation_type]
382
+ res[constraint] = getattr(annotation, constraint)
383
+ elif isinstance(annotation, type) and issubclass(annotation, PydanticMetadata):
384
+ # also support PydanticMetadata classes being used without initialisation,
385
+ # e.g. `Annotated[int, Strict]` as well as `Annotated[int, Strict()]`
386
+ res.update({k: v for k, v in vars(annotation).items() if not k.startswith('_')})
387
+ else:
388
+ remaining.append(annotation)
389
+ # Nones can sneak in but pydantic-core will reject them
390
+ # it'd be nice to clean things up so we don't put in None (we probably don't _need_ to, it was just easier)
391
+ # but this is simple enough to kick that can down the road
392
+ res = {k: v for k, v in res.items() if v is not None}
393
+ return res, remaining
394
+
395
+
396
+ def check_metadata(metadata: dict[str, Any], allowed: Iterable[str], source_type: Any) -> None:
397
+ """A small utility function to validate that the given metadata can be applied to the target.
398
+ More than saving lines of code, this gives us a consistent error message for all of our internal implementations.
399
+
400
+ Args:
401
+ metadata: A dict of metadata.
402
+ allowed: An iterable of allowed metadata.
403
+ source_type: The source type.
404
+
405
+ Raises:
406
+ TypeError: If there is metadatas that can't be applied on source type.
407
+ """
408
+ unknown = metadata.keys() - set(allowed)
409
+ if unknown:
410
+ raise TypeError(
411
+ f'The following constraints cannot be applied to {source_type!r}: {", ".join([f"{k!r}" for k in unknown])}'
412
+ )
@@ -0,0 +1,241 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, Iterator, Mapping
4
+ from typing import TYPE_CHECKING, Any, Generic, Literal, Protocol, TypeVar
5
+
6
+ from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator
7
+
8
+ from ..errors import PydanticErrorCodes, PydanticUserError
9
+ from ..plugin._schema_validator import PluggableSchemaValidator
10
+
11
+ if TYPE_CHECKING:
12
+ from ..dataclasses import PydanticDataclass
13
+ from ..main import BaseModel
14
+ from ..type_adapter import TypeAdapter
15
+
16
+
17
+ ValSer = TypeVar('ValSer', bound=SchemaValidator | PluggableSchemaValidator | SchemaSerializer)
18
+ T = TypeVar('T')
19
+ T_co = TypeVar('T_co', covariant=True)
20
+
21
+
22
+ class AttemptRebuild(Protocol[T_co]):
23
+ def __call__(self, *, parent_namespace_depth: int = ...) -> T_co | None: ...
24
+
25
+
26
+ class MockCoreSchema(Mapping[str, Any]):
27
+ """Mocker for `pydantic_core.CoreSchema` which optionally attempts to
28
+ rebuild the thing it's mocking when one of its methods is accessed and raises an error if that fails.
29
+ """
30
+
31
+ __slots__ = '_error_message', '_code', '_attempt_rebuild', '_built_memo'
32
+
33
+ def __init__(
34
+ self,
35
+ error_message: str,
36
+ *,
37
+ code: PydanticErrorCodes,
38
+ attempt_rebuild: AttemptRebuild[CoreSchema] | None = None,
39
+ ) -> None:
40
+ self._error_message = error_message
41
+ self._code: PydanticErrorCodes = code
42
+ self._attempt_rebuild = attempt_rebuild
43
+ self._built_memo: CoreSchema | None = None
44
+
45
+ def __getitem__(self, key: str) -> Any:
46
+ return self._get_built().__getitem__(key)
47
+
48
+ def __len__(self) -> int:
49
+ return self._get_built().__len__()
50
+
51
+ def __iter__(self) -> Iterator[str]:
52
+ return self._get_built().__iter__()
53
+
54
+ def _get_built(self) -> CoreSchema:
55
+ if self._built_memo is not None:
56
+ return self._built_memo
57
+
58
+ if self._attempt_rebuild:
59
+ schema = self._attempt_rebuild()
60
+ if schema is not None:
61
+ self._built_memo = schema
62
+ return schema
63
+ raise PydanticUserError(self._error_message, code=self._code)
64
+
65
+ def rebuild(self) -> CoreSchema | None:
66
+ self._built_memo = None
67
+ if self._attempt_rebuild:
68
+ schema = self._attempt_rebuild()
69
+ if schema is not None:
70
+ return schema
71
+ else:
72
+ raise PydanticUserError(self._error_message, code=self._code)
73
+ return None
74
+
75
+
76
+ class MockValSer(Generic[ValSer]):
77
+ """Mocker for `pydantic_core.SchemaValidator` or `pydantic_core.SchemaSerializer` which optionally attempts to
78
+ rebuild the thing it's mocking when one of its methods is accessed and raises an error if that fails.
79
+ """
80
+
81
+ __slots__ = '_error_message', '_code', '_val_or_ser', '_attempt_rebuild'
82
+
83
+ def __init__(
84
+ self,
85
+ error_message: str,
86
+ *,
87
+ code: PydanticErrorCodes,
88
+ val_or_ser: Literal['validator', 'serializer'],
89
+ attempt_rebuild: AttemptRebuild[ValSer] | None = None,
90
+ ) -> None:
91
+ self._error_message = error_message
92
+ self._val_or_ser = SchemaValidator if val_or_ser == 'validator' else SchemaSerializer
93
+ self._code: PydanticErrorCodes = code
94
+ self._attempt_rebuild = attempt_rebuild
95
+
96
+ def __getattr__(self, item: str) -> None:
97
+ __tracebackhide__ = True
98
+ # A slot name only reaches `__getattr__()` if it was never set, i.e. the instance was created without `__init__()`
99
+ # (when copying/unpickling).
100
+ if item in MockValSer.__slots__:
101
+ raise AttributeError(item)
102
+ if self._attempt_rebuild:
103
+ val_ser = self._attempt_rebuild()
104
+ if val_ser is not None:
105
+ return getattr(val_ser, item)
106
+
107
+ # raise an AttributeError if `item` doesn't exist
108
+ getattr(self._val_or_ser, item)
109
+ raise PydanticUserError(self._error_message, code=self._code)
110
+
111
+ def rebuild(self, *, parent_namespace_depth: int = 5) -> ValSer | None:
112
+ if self._attempt_rebuild:
113
+ val_ser = self._attempt_rebuild(parent_namespace_depth=parent_namespace_depth)
114
+ if val_ser is not None:
115
+ return val_ser
116
+ else:
117
+ raise PydanticUserError(self._error_message, code=self._code)
118
+ return None
119
+
120
+
121
+ def set_type_adapter_mocks(adapter: TypeAdapter) -> None:
122
+ """Set `core_schema`, `validator` and `serializer` to mock core types on a type adapter instance.
123
+
124
+ Args:
125
+ adapter: The type adapter instance to set the mocks on
126
+ """
127
+ type_repr = str(adapter._type)
128
+ undefined_type_error_message = (
129
+ f'`TypeAdapter[{type_repr}]` is not fully defined; you should define `{type_repr}` and all referenced types,'
130
+ f' then call `.rebuild()` on the instance.'
131
+ )
132
+
133
+ def attempt_rebuild_fn(attr_fn: Callable[[TypeAdapter], T]) -> AttemptRebuild[T]:
134
+ def handler(*, parent_namespace_depth: int = 5) -> T | None:
135
+ if adapter.rebuild(raise_errors=False, _parent_namespace_depth=parent_namespace_depth) is not False:
136
+ return attr_fn(adapter)
137
+ return None
138
+
139
+ return handler
140
+
141
+ adapter.core_schema = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue]
142
+ undefined_type_error_message,
143
+ code='class-not-fully-defined',
144
+ attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.core_schema),
145
+ )
146
+ adapter.validator = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
147
+ undefined_type_error_message,
148
+ code='class-not-fully-defined',
149
+ val_or_ser='validator',
150
+ attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.validator),
151
+ )
152
+ adapter.serializer = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
153
+ undefined_type_error_message,
154
+ code='class-not-fully-defined',
155
+ val_or_ser='serializer',
156
+ attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.serializer),
157
+ )
158
+
159
+
160
+ def set_model_mocks(cls: type[BaseModel], undefined_name: str | None = None) -> None:
161
+ """Set `__pydantic_core_schema__`, `__pydantic_validator__` and `__pydantic_serializer__` to mock core types on a model.
162
+
163
+ Args:
164
+ cls: The model class to set the mocks on
165
+ undefined_name: Name of the undefined thing, used in error messages
166
+ """
167
+ undefined_name = undefined_name if undefined_name is not None else 'all referenced types'
168
+
169
+ undefined_type_error_message = (
170
+ f'`{cls.__name__}` is not fully defined; you should define {undefined_name},'
171
+ f' then call `{cls.__name__}.model_rebuild()`.'
172
+ )
173
+
174
+ def attempt_rebuild_fn(attr_fn: Callable[[type[BaseModel]], T]) -> AttemptRebuild[T]:
175
+ def handler(*, parent_namespace_depth: int = 5) -> T | None:
176
+ if cls.model_rebuild(raise_errors=False, _parent_namespace_depth=parent_namespace_depth) is not False:
177
+ return attr_fn(cls)
178
+ return None
179
+
180
+ return handler
181
+
182
+ cls.__pydantic_core_schema__ = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue]
183
+ undefined_type_error_message,
184
+ code='class-not-fully-defined',
185
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_core_schema__),
186
+ )
187
+ cls.__pydantic_validator__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
188
+ undefined_type_error_message,
189
+ code='class-not-fully-defined',
190
+ val_or_ser='validator',
191
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_validator__),
192
+ )
193
+ cls.__pydantic_serializer__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
194
+ undefined_type_error_message,
195
+ code='class-not-fully-defined',
196
+ val_or_ser='serializer',
197
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_serializer__),
198
+ )
199
+
200
+
201
+ def set_dataclass_mocks(cls: type[PydanticDataclass], undefined_name: str | None = None) -> None:
202
+ """Set `__pydantic_validator__` and `__pydantic_serializer__` to `MockValSer`s on a dataclass.
203
+
204
+ Args:
205
+ cls: The model class to set the mocks on
206
+ undefined_name: Name of the undefined thing, used in error messages
207
+ """
208
+ from ..dataclasses import rebuild_dataclass
209
+
210
+ undefined_name = undefined_name if undefined_name is not None else 'all referenced types'
211
+
212
+ undefined_type_error_message = (
213
+ f'`{cls.__name__}` is not fully defined; you should define {undefined_name},'
214
+ f' then call `pboot_validator.dataclasses.rebuild_dataclass({cls.__name__})`.'
215
+ )
216
+
217
+ def attempt_rebuild_fn(attr_fn: Callable[[type[PydanticDataclass]], T]) -> AttemptRebuild[T]:
218
+ def handler(*, parent_namespace_depth: int = 5) -> T | None:
219
+ if rebuild_dataclass(cls, raise_errors=False, _parent_namespace_depth=parent_namespace_depth) is not False:
220
+ return attr_fn(cls)
221
+ return None
222
+
223
+ return handler
224
+
225
+ cls.__pydantic_core_schema__ = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue]
226
+ undefined_type_error_message,
227
+ code='class-not-fully-defined',
228
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_core_schema__),
229
+ )
230
+ cls.__pydantic_validator__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
231
+ undefined_type_error_message,
232
+ code='class-not-fully-defined',
233
+ val_or_ser='validator',
234
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_validator__),
235
+ )
236
+ cls.__pydantic_serializer__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
237
+ undefined_type_error_message,
238
+ code='class-not-fully-defined',
239
+ val_or_ser='serializer',
240
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_serializer__),
241
+ )