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,684 @@
1
+ """Experimental pipeline API functionality. Be careful with this API, it's subject to change."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import operator
7
+ import re
8
+ from collections import deque
9
+ from collections.abc import Callable, Container
10
+ from dataclasses import dataclass
11
+ from functools import cached_property, partial
12
+ from re import Pattern
13
+ from types import EllipsisType
14
+ from typing import TYPE_CHECKING, Annotated, Any, Generic, Protocol, TypeAlias, TypeVar, overload
15
+
16
+ import annotated_types
17
+ from typing_extensions import TypeForm
18
+
19
+ if TYPE_CHECKING:
20
+ from pboot_validator import GetCoreSchemaHandler
21
+
22
+ from pydantic_core import PydanticCustomError
23
+ from pydantic_core import core_schema as cs
24
+
25
+ from pboot_validator import Strict
26
+
27
+ __all__ = ['validate_as', 'validate_as_deferred', 'transform']
28
+
29
+
30
+ @dataclass(frozen=True, slots=True)
31
+ class _ValidateAs:
32
+ tp: TypeForm[Any]
33
+ strict: bool = False
34
+
35
+
36
+ @dataclass
37
+ class _ValidateAsDefer:
38
+ func: Callable[[], TypeForm[Any]]
39
+
40
+ @cached_property
41
+ def tp(self) -> TypeForm[Any]:
42
+ return self.func()
43
+
44
+
45
+ @dataclass(frozen=True, slots=True)
46
+ class _Transform:
47
+ func: Callable[[Any], Any]
48
+
49
+
50
+ @dataclass(frozen=True, slots=True)
51
+ class _PipelineOr:
52
+ left: _Pipeline[Any, Any]
53
+ right: _Pipeline[Any, Any]
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class _PipelineAnd:
58
+ left: _Pipeline[Any, Any]
59
+ right: _Pipeline[Any, Any]
60
+
61
+
62
+ @dataclass(frozen=True, slots=True)
63
+ class _Eq:
64
+ value: Any
65
+
66
+
67
+ @dataclass(frozen=True, slots=True)
68
+ class _NotEq:
69
+ value: Any
70
+
71
+
72
+ @dataclass(frozen=True, slots=True)
73
+ class _In:
74
+ values: Container[Any]
75
+
76
+
77
+ @dataclass(frozen=True, slots=True)
78
+ class _NotIn:
79
+ values: Container[Any]
80
+
81
+
82
+ _ConstraintAnnotation: TypeAlias = (
83
+ annotated_types.Le
84
+ | annotated_types.Ge
85
+ | annotated_types.Lt
86
+ | annotated_types.Gt
87
+ | annotated_types.Len
88
+ | annotated_types.MultipleOf
89
+ | annotated_types.Timezone
90
+ | annotated_types.Interval
91
+ | annotated_types.Predicate
92
+ |
93
+ # common predicates not included in annotated_types
94
+ _Eq
95
+ | _NotEq
96
+ | _In
97
+ | _NotIn
98
+ |
99
+ # regular expressions
100
+ Pattern[str]
101
+ )
102
+
103
+
104
+ @dataclass(frozen=True, slots=True)
105
+ class _Constraint:
106
+ constraint: _ConstraintAnnotation
107
+
108
+
109
+ _Step: TypeAlias = _ValidateAs | _ValidateAsDefer | _Transform | _PipelineOr | _PipelineAnd | _Constraint
110
+
111
+ _InT = TypeVar('_InT')
112
+ _OutT = TypeVar('_OutT')
113
+ _NewOutT = TypeVar('_NewOutT')
114
+
115
+
116
+ class _FieldTypeMarker:
117
+ pass
118
+
119
+
120
+ # TODO: ultimately, make this public, see https://github.com/pydantic/pydantic/pull/9459#discussion_r1628197626
121
+ # Also, make this frozen eventually, but that doesn't work right now because of the generic base
122
+ # Which attempts to modify __orig_base__ and such.
123
+ # We could go with a manual freeze, but that seems overkill for now.
124
+ @dataclass(slots=True)
125
+ class _Pipeline(Generic[_InT, _OutT]):
126
+ """Abstract representation of a chain of validation, transformation, and parsing steps."""
127
+
128
+ _steps: tuple[_Step, ...]
129
+
130
+ def transform(
131
+ self,
132
+ func: Callable[[_OutT], _NewOutT],
133
+ ) -> _Pipeline[_InT, _NewOutT]:
134
+ """Transform the output of the previous step.
135
+
136
+ If used as the first step in a pipeline, the type of the field is used.
137
+ That is, the transformation is applied to after the value is parsed to the field's type.
138
+ """
139
+ return _Pipeline[_InT, _NewOutT](self._steps + (_Transform(func),))
140
+
141
+ @overload
142
+ def validate_as(self, tp: TypeForm[_NewOutT], *, strict: bool = False) -> _Pipeline[_InT, _NewOutT]: ...
143
+
144
+ @overload
145
+ def validate_as(
146
+ self,
147
+ tp: EllipsisType,
148
+ *,
149
+ strict: bool = False,
150
+ ) -> _Pipeline[_InT, Any]: ...
151
+
152
+ def validate_as(self, tp: TypeForm[_NewOutT] | EllipsisType, *, strict: bool = False) -> _Pipeline[_InT, Any]: # type: ignore
153
+ """Validate / parse the input into a new type.
154
+
155
+ If no type is provided, the type of the field is used.
156
+
157
+ Types are parsed in Pydantic's `lax` mode by default,
158
+ but you can enable `strict` mode by passing `strict=True`.
159
+ """
160
+ if isinstance(tp, EllipsisType):
161
+ return _Pipeline[_InT, Any](self._steps + (_ValidateAs(_FieldTypeMarker, strict=strict),))
162
+ return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAs(tp, strict=strict),))
163
+
164
+ def validate_as_deferred(self, func: Callable[[], type[_NewOutT]]) -> _Pipeline[_InT, _NewOutT]:
165
+ """Parse the input into a new type, deferring resolution of the type until the current class
166
+ is fully defined.
167
+
168
+ This is useful when you need to reference the class in it's own type annotations.
169
+ """
170
+ return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAsDefer(func),))
171
+
172
+ # constraints
173
+ @overload
174
+ def constrain(self: _Pipeline[_InT, _NewOutGe], constraint: annotated_types.Ge) -> _Pipeline[_InT, _NewOutGe]: ...
175
+
176
+ @overload
177
+ def constrain(self: _Pipeline[_InT, _NewOutGt], constraint: annotated_types.Gt) -> _Pipeline[_InT, _NewOutGt]: ...
178
+
179
+ @overload
180
+ def constrain(self: _Pipeline[_InT, _NewOutLe], constraint: annotated_types.Le) -> _Pipeline[_InT, _NewOutLe]: ...
181
+
182
+ @overload
183
+ def constrain(self: _Pipeline[_InT, _NewOutLt], constraint: annotated_types.Lt) -> _Pipeline[_InT, _NewOutLt]: ...
184
+
185
+ @overload
186
+ def constrain(
187
+ self: _Pipeline[_InT, _NewOutLen], constraint: annotated_types.Len
188
+ ) -> _Pipeline[_InT, _NewOutLen]: ...
189
+
190
+ @overload
191
+ def constrain(
192
+ self: _Pipeline[_InT, _NewOutT], constraint: annotated_types.MultipleOf
193
+ ) -> _Pipeline[_InT, _NewOutT]: ...
194
+
195
+ @overload
196
+ def constrain(
197
+ self: _Pipeline[_InT, _NewOutDatetime], constraint: annotated_types.Timezone
198
+ ) -> _Pipeline[_InT, _NewOutDatetime]: ...
199
+
200
+ @overload
201
+ def constrain(self: _Pipeline[_InT, _OutT], constraint: annotated_types.Predicate) -> _Pipeline[_InT, _OutT]: ...
202
+
203
+ @overload
204
+ def constrain(
205
+ self: _Pipeline[_InT, _NewOutInterval], constraint: annotated_types.Interval
206
+ ) -> _Pipeline[_InT, _NewOutInterval]: ...
207
+
208
+ @overload
209
+ def constrain(self: _Pipeline[_InT, _OutT], constraint: _Eq) -> _Pipeline[_InT, _OutT]: ...
210
+
211
+ @overload
212
+ def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotEq) -> _Pipeline[_InT, _OutT]: ...
213
+
214
+ @overload
215
+ def constrain(self: _Pipeline[_InT, _OutT], constraint: _In) -> _Pipeline[_InT, _OutT]: ...
216
+
217
+ @overload
218
+ def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotIn) -> _Pipeline[_InT, _OutT]: ...
219
+
220
+ @overload
221
+ def constrain(self: _Pipeline[_InT, _NewOutT], constraint: Pattern[str]) -> _Pipeline[_InT, _NewOutT]: ...
222
+
223
+ def constrain(self, constraint: _ConstraintAnnotation) -> Any:
224
+ """Constrain a value to meet a certain condition.
225
+
226
+ We support most conditions from `annotated_types`, as well as regular expressions.
227
+
228
+ Most of the time you'll be calling a shortcut method like `gt`, `lt`, `len`, etc
229
+ so you don't need to call this directly.
230
+ """
231
+ return _Pipeline[_InT, _OutT](self._steps + (_Constraint(constraint),))
232
+
233
+ def predicate(self: _Pipeline[_InT, _NewOutT], func: Callable[[_NewOutT], bool]) -> _Pipeline[_InT, _NewOutT]:
234
+ """Constrain a value to meet a certain predicate."""
235
+ return self.constrain(annotated_types.Predicate(func))
236
+
237
+ def gt(self: _Pipeline[_InT, _NewOutGt], gt: _NewOutGt) -> _Pipeline[_InT, _NewOutGt]:
238
+ """Constrain a value to be greater than a certain value."""
239
+ return self.constrain(annotated_types.Gt(gt))
240
+
241
+ def lt(self: _Pipeline[_InT, _NewOutLt], lt: _NewOutLt) -> _Pipeline[_InT, _NewOutLt]:
242
+ """Constrain a value to be less than a certain value."""
243
+ return self.constrain(annotated_types.Lt(lt))
244
+
245
+ def ge(self: _Pipeline[_InT, _NewOutGe], ge: _NewOutGe) -> _Pipeline[_InT, _NewOutGe]:
246
+ """Constrain a value to be greater than or equal to a certain value."""
247
+ return self.constrain(annotated_types.Ge(ge))
248
+
249
+ def le(self: _Pipeline[_InT, _NewOutLe], le: _NewOutLe) -> _Pipeline[_InT, _NewOutLe]:
250
+ """Constrain a value to be less than or equal to a certain value."""
251
+ return self.constrain(annotated_types.Le(le))
252
+
253
+ def len(self: _Pipeline[_InT, _NewOutLen], min_len: int, max_len: int | None = None) -> _Pipeline[_InT, _NewOutLen]:
254
+ """Constrain a value to have a certain length."""
255
+ return self.constrain(annotated_types.Len(min_len, max_len))
256
+
257
+ @overload
258
+ def multiple_of(self: _Pipeline[_InT, _NewOutDiv], multiple_of: _NewOutDiv) -> _Pipeline[_InT, _NewOutDiv]: ...
259
+
260
+ @overload
261
+ def multiple_of(self: _Pipeline[_InT, _NewOutMod], multiple_of: _NewOutMod) -> _Pipeline[_InT, _NewOutMod]: ...
262
+
263
+ def multiple_of(self: _Pipeline[_InT, Any], multiple_of: Any) -> _Pipeline[_InT, Any]:
264
+ """Constrain a value to be a multiple of a certain number."""
265
+ return self.constrain(annotated_types.MultipleOf(multiple_of))
266
+
267
+ def eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]:
268
+ """Constrain a value to be equal to a certain value."""
269
+ return self.constrain(_Eq(value))
270
+
271
+ def not_eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]:
272
+ """Constrain a value to not be equal to a certain value."""
273
+ return self.constrain(_NotEq(value))
274
+
275
+ def in_(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]:
276
+ """Constrain a value to be in a certain set."""
277
+ return self.constrain(_In(values))
278
+
279
+ def not_in(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]:
280
+ """Constrain a value to not be in a certain set."""
281
+ return self.constrain(_NotIn(values))
282
+
283
+ # timezone methods
284
+ def datetime_tz_naive(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]:
285
+ """Constrain a datetime value to be timezone-naive (i.e. have no tzinfo)."""
286
+ return self.constrain(annotated_types.Timezone(None))
287
+
288
+ def datetime_tz_aware(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]:
289
+ """Constrain a datetime value to be timezone-aware (i.e. have a non-None tzinfo)."""
290
+ return self.constrain(annotated_types.Timezone(...))
291
+
292
+ def datetime_tz(
293
+ self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo
294
+ ) -> _Pipeline[_InT, datetime.datetime]:
295
+ """Constrain a datetime value to have a specific timezone.
296
+
297
+ Args:
298
+ tz: The required timezone.
299
+ """
300
+ return self.constrain(annotated_types.Timezone(tz)) # type: ignore
301
+
302
+ def datetime_with_tz(
303
+ self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo | None
304
+ ) -> _Pipeline[_InT, datetime.datetime]:
305
+ """Transform a datetime value by replacing its timezone with the given value.
306
+
307
+ Unlike `datetime_tz()`, this does not validate the existing timezone, it
308
+ unconditionally sets [`tzinfo`][datetime.datetime.tzinfo] to `tz`.
309
+
310
+ Args:
311
+ tz: The timezone to attach to the datetime, or `None` to make it naive.
312
+ """
313
+ return self.transform(partial(datetime.datetime.replace, tzinfo=tz))
314
+
315
+ # string methods
316
+ def str_lower(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
317
+ """Transform a string value to [lowercase][str.lower]."""
318
+ return self.transform(str.lower)
319
+
320
+ def str_upper(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
321
+ """Transform a string value to [uppercase][str.upper]."""
322
+ return self.transform(str.upper)
323
+
324
+ def str_title(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
325
+ """Transform a string value to [title case][str.title]."""
326
+ return self.transform(str.title)
327
+
328
+ def str_strip(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
329
+ """Strip leading and trailing whitespace from a string value."""
330
+ return self.transform(str.strip)
331
+
332
+ def str_pattern(self: _Pipeline[_InT, str], pattern: str) -> _Pipeline[_InT, str]:
333
+ """Constrain a string value to match a regular expression pattern.
334
+
335
+ Args:
336
+ pattern: The regular expression pattern the string must match.
337
+ """
338
+ return self.constrain(re.compile(pattern))
339
+
340
+ def str_contains(self: _Pipeline[_InT, str], substring: str) -> _Pipeline[_InT, str]:
341
+ """Constrain a string value to contain a given substring.
342
+
343
+ Args:
344
+ substring: The substring that must be present in the string.
345
+ """
346
+ return self.predicate(lambda v: substring in v)
347
+
348
+ def str_starts_with(self: _Pipeline[_InT, str], prefix: str) -> _Pipeline[_InT, str]:
349
+ """Constrain a string value to start with a given prefix.
350
+
351
+ Args:
352
+ prefix: The prefix the string must start with.
353
+ """
354
+ return self.predicate(lambda v: v.startswith(prefix))
355
+
356
+ def str_ends_with(self: _Pipeline[_InT, str], suffix: str) -> _Pipeline[_InT, str]:
357
+ """Constrain a string value to end with a given suffix.
358
+
359
+ Args:
360
+ suffix: The suffix the string must end with.
361
+ """
362
+ return self.predicate(lambda v: v.endswith(suffix))
363
+
364
+ # operators
365
+ def otherwise(self, other: _Pipeline[_OtherIn, _OtherOut]) -> _Pipeline[_InT | _OtherIn, _OutT | _OtherOut]:
366
+ """Combine two validation chains, returning the result of the first chain if it succeeds, and the second chain if it fails."""
367
+ return _Pipeline((_PipelineOr(self, other),))
368
+
369
+ __or__ = otherwise
370
+
371
+ def then(self, other: _Pipeline[_OutT, _OtherOut]) -> _Pipeline[_InT, _OtherOut]:
372
+ """Pipe the result of one validation chain into another."""
373
+ return _Pipeline((_PipelineAnd(self, other),))
374
+
375
+ __and__ = then
376
+
377
+ def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> cs.CoreSchema:
378
+ return self._apply_pipeline(handler, source_type)
379
+
380
+ def _apply_pipeline(self, handler: GetCoreSchemaHandler, source_type: Any) -> cs.CoreSchema:
381
+ queue = deque(self._steps)
382
+
383
+ s = None
384
+
385
+ while queue:
386
+ step = queue.popleft()
387
+ s = _apply_step(step, s, handler, source_type)
388
+
389
+ s = s or cs.any_schema()
390
+ return s
391
+
392
+ def __supports_type__(self, _: _OutT) -> bool:
393
+ raise NotImplementedError
394
+
395
+
396
+ validate_as = _Pipeline[Any, Any](()).validate_as
397
+ validate_as_deferred = _Pipeline[Any, Any](()).validate_as_deferred
398
+ transform = _Pipeline[Any, Any]((_ValidateAs(_FieldTypeMarker),)).transform
399
+
400
+
401
+ def _check_func(
402
+ func: Callable[[Any], bool], predicate_err: str | Callable[[], str], s: cs.CoreSchema | None
403
+ ) -> cs.CoreSchema:
404
+ def handler(v: Any) -> Any:
405
+ if func(v):
406
+ return v
407
+ raise ValueError(f'Expected {predicate_err if isinstance(predicate_err, str) else predicate_err()}')
408
+
409
+ if s is None:
410
+ return cs.no_info_plain_validator_function(handler)
411
+ else:
412
+ return cs.no_info_after_validator_function(handler, s)
413
+
414
+
415
+ def _apply_step(step: _Step, s: cs.CoreSchema | None, handler: GetCoreSchemaHandler, source_type: Any) -> cs.CoreSchema:
416
+ if isinstance(step, _ValidateAs):
417
+ s = _apply_parse(s, step.tp, step.strict, handler, source_type)
418
+ elif isinstance(step, _ValidateAsDefer):
419
+ s = _apply_parse(s, step.tp, False, handler, source_type)
420
+ elif isinstance(step, _Transform):
421
+ s = _apply_transform(s, step.func, handler)
422
+ elif isinstance(step, _Constraint):
423
+ s = _apply_constraint(s, step.constraint)
424
+ elif isinstance(step, _PipelineOr):
425
+ s = cs.union_schema(
426
+ [step.left._apply_pipeline(handler, source_type), step.right._apply_pipeline(handler, source_type)]
427
+ )
428
+ else:
429
+ assert isinstance(step, _PipelineAnd)
430
+ s = cs.chain_schema(
431
+ [step.left._apply_pipeline(handler, source_type), step.right._apply_pipeline(handler, source_type)]
432
+ )
433
+ return s
434
+
435
+
436
+ def _apply_parse(
437
+ s: cs.CoreSchema | None,
438
+ tp: TypeForm[Any],
439
+ strict: bool,
440
+ handler: GetCoreSchemaHandler,
441
+ source_type: Any,
442
+ ) -> cs.CoreSchema:
443
+ if tp is _FieldTypeMarker:
444
+ return cs.chain_schema([s, handler(source_type)]) if s else handler(source_type)
445
+
446
+ if strict:
447
+ tp = Annotated[tp, Strict()] # type: ignore
448
+
449
+ if s and s['type'] == 'any':
450
+ return handler(tp)
451
+ else:
452
+ return cs.chain_schema([s, handler(tp)]) if s else handler(tp)
453
+
454
+
455
+ def _apply_transform(
456
+ s: cs.CoreSchema | None, func: Callable[[Any], Any], handler: GetCoreSchemaHandler
457
+ ) -> cs.CoreSchema:
458
+ if s is None:
459
+ return cs.no_info_plain_validator_function(func)
460
+
461
+ if s['type'] == 'str':
462
+ if func is str.strip:
463
+ s = s.copy()
464
+ s['strip_whitespace'] = True
465
+ return s
466
+ elif func is str.lower:
467
+ s = s.copy()
468
+ s['to_lower'] = True
469
+ return s
470
+ elif func is str.upper:
471
+ s = s.copy()
472
+ s['to_upper'] = True
473
+ return s
474
+
475
+ return cs.no_info_after_validator_function(func, s)
476
+
477
+
478
+ # Core schema types with native support for the `gt`/`ge`/`lt`/`le` constraints:
479
+ _ORDERING_SCHEMA_TYPES = frozenset({'int', 'float', 'decimal', 'fraction', 'date', 'time', 'datetime', 'timedelta'})
480
+ # Core schema types with native support for the `min_length`/`max_length` constraints:
481
+ _LENGTH_SCHEMA_TYPES = frozenset(
482
+ {'str', 'bytes', 'list', 'tuple', 'set', 'frozenset', 'dict', 'frozendict', 'ordered-dict', 'counter', 'generator'}
483
+ )
484
+
485
+
486
+ def _apply_constraint( # noqa: C901
487
+ s: cs.CoreSchema | None, constraint: _ConstraintAnnotation
488
+ ) -> cs.CoreSchema:
489
+ """Apply a single constraint to a schema."""
490
+ # No casting of the constraints is necessary, as pydantic-core does it
491
+ # when building the validator from the core schema:
492
+ if isinstance(constraint, annotated_types.Gt):
493
+ gt = constraint.gt
494
+ if s and s['type'] in _ORDERING_SCHEMA_TYPES:
495
+ s = s.copy()
496
+ s['gt'] = gt # pyright: ignore[reportGeneralTypeIssues]
497
+ else:
498
+
499
+ def check_gt(v: Any) -> bool:
500
+ return v > gt
501
+
502
+ s = _check_func(check_gt, f'> {gt}', s)
503
+ elif isinstance(constraint, annotated_types.Ge):
504
+ ge = constraint.ge
505
+ if s and s['type'] in _ORDERING_SCHEMA_TYPES:
506
+ s = s.copy()
507
+ s['ge'] = ge # pyright: ignore[reportGeneralTypeIssues]
508
+ else:
509
+
510
+ def check_ge(v: Any) -> bool:
511
+ return v >= ge
512
+
513
+ s = _check_func(check_ge, f'>= {ge}', s)
514
+ elif isinstance(constraint, annotated_types.Lt):
515
+ lt = constraint.lt
516
+ if s and s['type'] in _ORDERING_SCHEMA_TYPES:
517
+ s = s.copy()
518
+ s['lt'] = lt # pyright: ignore[reportGeneralTypeIssues]
519
+ else:
520
+
521
+ def check_lt(v: Any) -> bool:
522
+ return v < lt
523
+
524
+ s = _check_func(check_lt, f'< {lt}', s)
525
+ elif isinstance(constraint, annotated_types.Le):
526
+ le = constraint.le
527
+ if s and s['type'] in _ORDERING_SCHEMA_TYPES:
528
+ s = s.copy()
529
+ s['le'] = le # pyright: ignore[reportGeneralTypeIssues]
530
+ else:
531
+
532
+ def check_le(v: Any) -> bool:
533
+ return v <= le
534
+
535
+ s = _check_func(check_le, f'<= {le}', s)
536
+ elif isinstance(constraint, annotated_types.Len):
537
+ min_len = constraint.min_length
538
+ max_len = constraint.max_length
539
+
540
+ if s and s['type'] in _LENGTH_SCHEMA_TYPES:
541
+ s = s.copy()
542
+ if min_len != 0:
543
+ s['min_length'] = min_len # pyright: ignore[reportGeneralTypeIssues]
544
+ if max_len is not None:
545
+ s['max_length'] = max_len # pyright: ignore[reportGeneralTypeIssues]
546
+ else:
547
+
548
+ def check_len(v: Any) -> bool:
549
+ len_v = len(v)
550
+ if max_len is not None:
551
+ return min_len <= len_v <= max_len
552
+ return min_len <= len_v
553
+
554
+ predicate_err = (
555
+ f'length >= {min_len}' if max_len is None else f'length >= {min_len} and length <= {max_len}'
556
+ )
557
+ s = _check_func(check_len, predicate_err, s)
558
+ elif isinstance(constraint, annotated_types.MultipleOf):
559
+ multiple_of = constraint.multiple_of
560
+ if s and s['type'] in {'int', 'float', 'decimal'}:
561
+ s = s.copy()
562
+ s['multiple_of'] = multiple_of # pyright: ignore[reportGeneralTypeIssues]
563
+ else:
564
+
565
+ def check_multiple_of(v: Any) -> bool:
566
+ return v % multiple_of == 0
567
+
568
+ s = _check_func(check_multiple_of, f'% {multiple_of} == 0', s)
569
+ elif isinstance(constraint, annotated_types.Timezone):
570
+ tz = constraint.tz
571
+
572
+ if tz is ...:
573
+ if s and s['type'] == 'datetime':
574
+ s = s.copy()
575
+ s['tz_constraint'] = 'aware'
576
+ else:
577
+
578
+ def check_tz_aware(v: object) -> bool:
579
+ assert isinstance(v, datetime.datetime)
580
+ return v.tzinfo is not None
581
+
582
+ s = _check_func(check_tz_aware, 'timezone aware', s)
583
+ elif tz is None:
584
+ if s and s['type'] == 'datetime':
585
+ s = s.copy()
586
+ s['tz_constraint'] = 'naive'
587
+ else:
588
+
589
+ def check_tz_naive(v: object) -> bool:
590
+ assert isinstance(v, datetime.datetime)
591
+ return v.tzinfo is None
592
+
593
+ s = _check_func(check_tz_naive, 'timezone naive', s)
594
+ else:
595
+ raise NotImplementedError('Constraining to a specific timezone is not yet supported')
596
+ elif isinstance(constraint, annotated_types.Interval):
597
+ if constraint.ge is not None:
598
+ s = _apply_constraint(s, annotated_types.Ge(constraint.ge))
599
+ if constraint.gt is not None:
600
+ s = _apply_constraint(s, annotated_types.Gt(constraint.gt))
601
+ if constraint.le is not None:
602
+ s = _apply_constraint(s, annotated_types.Le(constraint.le))
603
+ if constraint.lt is not None:
604
+ s = _apply_constraint(s, annotated_types.Lt(constraint.lt))
605
+ assert s is not None
606
+ elif isinstance(constraint, annotated_types.Predicate):
607
+ func = constraint.func
608
+ # Same logic as in `_known_annotated_metadata.apply_known_metadata()`:
609
+ predicate_name = f'{func.__qualname__!r} ' if hasattr(func, '__qualname__') else ''
610
+
611
+ def predicate_func(v: Any) -> Any:
612
+ if not func(v):
613
+ raise PydanticCustomError(
614
+ 'predicate_failed',
615
+ f'Predicate {predicate_name}failed', # pyright: ignore[reportArgumentType]
616
+ )
617
+ return v
618
+
619
+ if s is None:
620
+ s = cs.no_info_plain_validator_function(predicate_func)
621
+ else:
622
+ s = cs.no_info_after_validator_function(predicate_func, s)
623
+ elif isinstance(constraint, _NotEq):
624
+ value = constraint.value
625
+
626
+ def check_not_eq(v: Any) -> bool:
627
+ return operator.__ne__(v, value)
628
+
629
+ s = _check_func(check_not_eq, f'!= {value}', s)
630
+ elif isinstance(constraint, _Eq):
631
+ value = constraint.value
632
+
633
+ def check_eq(v: Any) -> bool:
634
+ return operator.__eq__(v, value)
635
+
636
+ s = _check_func(check_eq, f'== {value}', s)
637
+ elif isinstance(constraint, _In):
638
+ values = constraint.values
639
+
640
+ def check_in(v: Any) -> bool:
641
+ return operator.__contains__(values, v)
642
+
643
+ s = _check_func(check_in, f'in {values}', s)
644
+ elif isinstance(constraint, _NotIn):
645
+ values = constraint.values
646
+
647
+ def check_not_in(v: Any) -> bool:
648
+ return operator.__not__(operator.__contains__(values, v))
649
+
650
+ s = _check_func(check_not_in, f'not in {values}', s)
651
+ else:
652
+ assert isinstance(constraint, Pattern)
653
+ if s and s['type'] == 'str':
654
+ s = s.copy()
655
+ s['pattern'] = constraint
656
+ else:
657
+
658
+ def check_pattern(v: object) -> bool:
659
+ assert isinstance(v, str)
660
+ return constraint.match(v) is not None
661
+
662
+ s = _check_func(check_pattern, f'~ {constraint.pattern}', s)
663
+ return s
664
+
665
+
666
+ class _SupportsRange(annotated_types.SupportsLe, annotated_types.SupportsGe, Protocol):
667
+ pass
668
+
669
+
670
+ class _SupportsLen(Protocol):
671
+ def __len__(self) -> int: ...
672
+
673
+
674
+ _NewOutGt = TypeVar('_NewOutGt', bound=annotated_types.SupportsGt)
675
+ _NewOutGe = TypeVar('_NewOutGe', bound=annotated_types.SupportsGe)
676
+ _NewOutLt = TypeVar('_NewOutLt', bound=annotated_types.SupportsLt)
677
+ _NewOutLe = TypeVar('_NewOutLe', bound=annotated_types.SupportsLe)
678
+ _NewOutLen = TypeVar('_NewOutLen', bound=_SupportsLen)
679
+ _NewOutDiv = TypeVar('_NewOutDiv', bound=annotated_types.SupportsDiv)
680
+ _NewOutMod = TypeVar('_NewOutMod', bound=annotated_types.SupportsMod)
681
+ _NewOutDatetime = TypeVar('_NewOutDatetime', bound=datetime.datetime)
682
+ _NewOutInterval = TypeVar('_NewOutInterval', bound=_SupportsRange)
683
+ _OtherIn = TypeVar('_OtherIn')
684
+ _OtherOut = TypeVar('_OtherOut')