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,433 @@
1
+ """Bucket of reusable internal utilities.
2
+
3
+ This should be reduced as much as possible with functions only used in one place, moved to that place.
4
+ """
5
+
6
+ from __future__ import annotations as _annotations
7
+
8
+ import dataclasses
9
+ import keyword
10
+ import warnings
11
+ import weakref
12
+ from collections import OrderedDict, defaultdict, deque
13
+ from collections.abc import Callable, Iterable, Mapping
14
+ from collections.abc import Set as AbstractSet
15
+ from copy import deepcopy
16
+ from functools import cached_property
17
+ from inspect import Parameter
18
+ from itertools import zip_longest
19
+ from types import BuiltinFunctionType, CodeType, FunctionType, GeneratorType, LambdaType, ModuleType, NoneType
20
+ from typing import TYPE_CHECKING, Any, Generic, TypeAlias, TypeGuard, TypeVar, overload
21
+
22
+ from pydantic_core import MISSING, PydanticUndefined
23
+ from typing_extensions import deprecated
24
+
25
+ from pboot_validator import PydanticDeprecatedSince211
26
+
27
+ from . import _repr, _typing_extra
28
+ from ._import_utils import import_cached_base_model
29
+
30
+ if TYPE_CHECKING:
31
+ MappingIntStrAny: TypeAlias = Mapping[int, Any] | Mapping[str, Any]
32
+ AbstractSetIntStr: TypeAlias = AbstractSet[int] | AbstractSet[str]
33
+ from ..main import BaseModel
34
+
35
+
36
+ # these are types that are returned unchanged by deepcopy
37
+ IMMUTABLE_NON_COLLECTIONS_TYPES: set[type[Any]] = {
38
+ int,
39
+ float,
40
+ complex,
41
+ str,
42
+ bool,
43
+ bytes,
44
+ type,
45
+ NoneType,
46
+ FunctionType,
47
+ BuiltinFunctionType,
48
+ LambdaType,
49
+ weakref.ref,
50
+ CodeType,
51
+ # note: including ModuleType will differ from behaviour of deepcopy by not producing error.
52
+ # It might be not a good idea in general, but considering that this function used only internally
53
+ # against default values of fields, this will allow one to actually have a field with module as default value
54
+ ModuleType,
55
+ NotImplemented.__class__,
56
+ Ellipsis.__class__,
57
+ }
58
+
59
+ # these are types that if empty, might be copied with simple copy() instead of deepcopy()
60
+ BUILTIN_COLLECTIONS: set[type[Any]] = {
61
+ list,
62
+ set,
63
+ tuple,
64
+ frozenset,
65
+ dict,
66
+ OrderedDict,
67
+ defaultdict,
68
+ deque,
69
+ }
70
+
71
+
72
+ def can_be_positional(param: Parameter) -> bool:
73
+ """Return whether the parameter accepts a positional argument.
74
+
75
+ ```python {test="skip" lint="skip"}
76
+ def func(a, /, b, *, c):
77
+ pass
78
+
79
+ params = inspect.signature(func).parameters
80
+ can_be_positional(params['a'])
81
+ #> True
82
+ can_be_positional(params['b'])
83
+ #> True
84
+ can_be_positional(params['c'])
85
+ #> False
86
+ ```
87
+ """
88
+ return param.kind in (Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD)
89
+
90
+
91
+ def sequence_like(v: Any) -> bool:
92
+ return isinstance(v, (list, tuple, set, frozenset, GeneratorType, deque))
93
+
94
+
95
+ def lenient_isinstance(o: Any, class_or_tuple: type[Any] | tuple[type[Any], ...] | None) -> bool: # pragma: no cover
96
+ try:
97
+ return isinstance(o, class_or_tuple) # type: ignore[arg-type]
98
+ except TypeError:
99
+ return False
100
+
101
+
102
+ def lenient_issubclass(cls: Any, class_or_tuple: Any) -> bool: # pragma: no cover
103
+ try:
104
+ return isinstance(cls, type) and issubclass(cls, class_or_tuple)
105
+ except TypeError:
106
+ if isinstance(cls, _typing_extra.WithArgsTypes):
107
+ return False
108
+ raise # pragma: no cover
109
+
110
+
111
+ def is_model_class(cls: Any) -> TypeGuard[type[BaseModel]]:
112
+ """Returns true if cls is a _proper_ subclass of BaseModel, and provides proper type-checking,
113
+ unlike raw calls to lenient_issubclass.
114
+ """
115
+ BaseModel = import_cached_base_model()
116
+
117
+ return lenient_issubclass(cls, BaseModel) and cls is not BaseModel
118
+
119
+
120
+ def is_valid_identifier(identifier: str) -> bool:
121
+ """Checks that a string is a valid identifier and not a Python keyword.
122
+ :param identifier: The identifier to test.
123
+ :return: True if the identifier is valid.
124
+ """
125
+ return identifier.isidentifier() and not keyword.iskeyword(identifier)
126
+
127
+
128
+ KeyType = TypeVar('KeyType')
129
+
130
+
131
+ def deep_update(mapping: dict[KeyType, Any], *updating_mappings: dict[KeyType, Any]) -> dict[KeyType, Any]:
132
+ updated_mapping = mapping.copy()
133
+ for updating_mapping in updating_mappings:
134
+ for k, v in updating_mapping.items():
135
+ if k in updated_mapping and isinstance(updated_mapping[k], dict) and isinstance(v, dict):
136
+ updated_mapping[k] = deep_update(updated_mapping[k], v)
137
+ else:
138
+ updated_mapping[k] = v
139
+ return updated_mapping
140
+
141
+
142
+ def update_not_none(mapping: dict[Any, Any], **update: Any) -> None:
143
+ mapping.update({k: v for k, v in update.items() if v is not None})
144
+
145
+
146
+ T = TypeVar('T')
147
+
148
+
149
+ def unique_list(
150
+ input_list: list[T] | tuple[T, ...],
151
+ *,
152
+ name_factory: Callable[[T], str] = str,
153
+ ) -> list[T]:
154
+ """Make a list unique while maintaining order.
155
+ We update the list if another one with the same name is set
156
+ (e.g. model validator overridden in subclass).
157
+ """
158
+ result: list[T] = []
159
+ result_names: list[str] = []
160
+ for v in input_list:
161
+ v_name = name_factory(v)
162
+ if v_name not in result_names:
163
+ result_names.append(v_name)
164
+ result.append(v)
165
+ else:
166
+ result[result_names.index(v_name)] = v
167
+
168
+ return result
169
+
170
+
171
+ class ValueItems(_repr.Representation):
172
+ """Class for more convenient calculation of excluded or included fields on values."""
173
+
174
+ __slots__ = ('_items',)
175
+
176
+ def __init__(self, value: Any, items: AbstractSetIntStr | MappingIntStrAny) -> None:
177
+ items = self._coerce_items(items)
178
+
179
+ if isinstance(value, (list, tuple)):
180
+ items = self._normalize_indexes(items, len(value)) # type: ignore
181
+
182
+ self._items: MappingIntStrAny = items # type: ignore
183
+
184
+ def is_excluded(self, item: Any) -> bool:
185
+ """Check if item is fully excluded.
186
+
187
+ :param item: key or index of a value
188
+ """
189
+ return self.is_true(self._items.get(item))
190
+
191
+ def is_included(self, item: Any) -> bool:
192
+ """Check if value is contained in self._items.
193
+
194
+ :param item: key or index of value
195
+ """
196
+ return item in self._items
197
+
198
+ def for_element(self, e: int | str) -> AbstractSetIntStr | MappingIntStrAny | None:
199
+ """:param e: key or index of element on value
200
+ :return: raw values for element if self._items is dict and contain needed element
201
+ """
202
+ item = self._items.get(e) # type: ignore
203
+ return item if not self.is_true(item) else None
204
+
205
+ def _normalize_indexes(self, items: MappingIntStrAny, v_length: int) -> dict[int | str, Any]:
206
+ """:param items: dict or set of indexes which will be normalized
207
+ :param v_length: length of sequence indexes of which will be
208
+
209
+ >>> self._normalize_indexes({0: True, -2: True, -1: True}, 4)
210
+ {0: True, 2: True, 3: True}
211
+ >>> self._normalize_indexes({'__all__': True}, 4)
212
+ {0: True, 1: True, 2: True, 3: True}
213
+ """
214
+ normalized_items: dict[int | str, Any] = {}
215
+ all_items = None
216
+ for i, v in items.items():
217
+ if not (isinstance(v, Mapping) or isinstance(v, AbstractSet) or self.is_true(v)):
218
+ raise TypeError(f'Unexpected type of exclude value for index "{i}" {v.__class__}')
219
+ if i == '__all__':
220
+ all_items = self._coerce_value(v)
221
+ continue
222
+ if not isinstance(i, int):
223
+ raise TypeError(
224
+ 'Excluding fields from a sequence of sub-models or dicts must be performed index-wise: '
225
+ 'expected integer keys or keyword "__all__"'
226
+ )
227
+ normalized_i = v_length + i if i < 0 else i
228
+ normalized_items[normalized_i] = self.merge(v, normalized_items.get(normalized_i))
229
+
230
+ if not all_items:
231
+ return normalized_items
232
+ if self.is_true(all_items):
233
+ for i in range(v_length):
234
+ normalized_items.setdefault(i, ...)
235
+ return normalized_items
236
+ for i in range(v_length):
237
+ normalized_item = normalized_items.setdefault(i, {})
238
+ if not self.is_true(normalized_item):
239
+ normalized_items[i] = self.merge(all_items, normalized_item)
240
+ return normalized_items
241
+
242
+ @classmethod
243
+ def merge(cls, base: Any, override: Any, intersect: bool = False) -> Any:
244
+ """Merge a `base` item with an `override` item.
245
+
246
+ Both `base` and `override` are converted to dictionaries if possible.
247
+ Sets are converted to dictionaries with the sets entries as keys and
248
+ Ellipsis as values.
249
+
250
+ Each key-value pair existing in `base` is merged with `override`,
251
+ while the rest of the key-value pairs are updated recursively with this function.
252
+
253
+ Merging takes place based on the "union" of keys if `intersect` is
254
+ set to `False` (default) and on the intersection of keys if
255
+ `intersect` is set to `True`.
256
+ """
257
+ override = cls._coerce_value(override)
258
+ base = cls._coerce_value(base)
259
+ if override is None:
260
+ return base
261
+ if cls.is_true(base) or base is None:
262
+ return override
263
+ if cls.is_true(override):
264
+ return base if intersect else override
265
+
266
+ # intersection or union of keys while preserving ordering:
267
+ if intersect:
268
+ merge_keys = [k for k in base if k in override] + [k for k in override if k in base]
269
+ else:
270
+ merge_keys = list(base) + [k for k in override if k not in base]
271
+
272
+ merged: dict[int | str, Any] = {}
273
+ for k in merge_keys:
274
+ merged_item = cls.merge(base.get(k), override.get(k), intersect=intersect)
275
+ if merged_item is not None:
276
+ merged[k] = merged_item
277
+
278
+ return merged
279
+
280
+ @staticmethod
281
+ def _coerce_items(items: AbstractSetIntStr | MappingIntStrAny) -> MappingIntStrAny:
282
+ if isinstance(items, Mapping):
283
+ pass
284
+ elif isinstance(items, AbstractSet):
285
+ items = dict.fromkeys(items, ...) # type: ignore
286
+ else:
287
+ class_name = getattr(items, '__class__', '???')
288
+ raise TypeError(f'Unexpected type of exclude value {class_name}')
289
+ return items # type: ignore
290
+
291
+ @classmethod
292
+ def _coerce_value(cls, value: Any) -> Any:
293
+ if value is None or cls.is_true(value):
294
+ return value
295
+ return cls._coerce_items(value)
296
+
297
+ @staticmethod
298
+ def is_true(v: Any) -> bool:
299
+ return v is True or v is ...
300
+
301
+ def __repr_args__(self) -> _repr.ReprArgs:
302
+ return [(None, self._items)]
303
+
304
+
305
+ if TYPE_CHECKING:
306
+
307
+ def LazyClassAttribute(name: str, get_value: Callable[[], T]) -> T: ...
308
+
309
+ else:
310
+
311
+ class LazyClassAttribute:
312
+ """A descriptor exposing an attribute only accessible on a class (hidden from instances).
313
+
314
+ The attribute is lazily computed and cached during the first access.
315
+ """
316
+
317
+ def __init__(self, name: str, get_value: Callable[[], Any]) -> None:
318
+ self.name = name
319
+ self.get_value = get_value
320
+
321
+ @cached_property
322
+ def value(self) -> Any:
323
+ return self.get_value()
324
+
325
+ def __get__(self, instance: Any, owner: type[Any]) -> Any:
326
+ if instance is None:
327
+ return self.value
328
+ raise AttributeError(f'{self.name!r} attribute of {owner.__name__!r} is class-only')
329
+
330
+
331
+ Obj = TypeVar('Obj')
332
+
333
+
334
+ def smart_deepcopy(obj: Obj) -> Obj:
335
+ """Return type as is for immutable built-in types
336
+ Use obj.copy() for built-in empty collections
337
+ Use copy.deepcopy() for non-empty collections and unknown objects.
338
+ """
339
+ if obj is MISSING or obj is PydanticUndefined:
340
+ return obj # pyright: ignore[reportReturnType]
341
+ obj_type = obj.__class__
342
+ if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES:
343
+ return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway
344
+ try:
345
+ if not obj and obj_type in BUILTIN_COLLECTIONS:
346
+ # faster way for empty collections, no need to copy its members
347
+ return obj if obj_type is tuple else obj.copy() # tuple doesn't have copy method # type: ignore
348
+ except (TypeError, ValueError, RuntimeError):
349
+ # do we really dare to catch ALL errors? Seems a bit risky
350
+ pass
351
+
352
+ return deepcopy(obj) # slowest way when we actually might need a deepcopy
353
+
354
+
355
+ _SENTINEL = object()
356
+
357
+
358
+ def all_identical(left: Iterable[Any], right: Iterable[Any]) -> bool:
359
+ """Check that the items of `left` are the same objects as those in `right`.
360
+
361
+ >>> a, b = object(), object()
362
+ >>> all_identical([a, b, a], [a, b, a])
363
+ True
364
+ >>> all_identical([a, b, [a]], [a, b, [a]]) # new list object, while "equal" is not "identical"
365
+ False
366
+ """
367
+ for left_item, right_item in zip_longest(left, right, fillvalue=_SENTINEL):
368
+ if left_item is not right_item:
369
+ return False
370
+ return True
371
+
372
+
373
+ def get_first_not_none(a: Any, b: Any) -> Any:
374
+ """Return the first argument if it is not `None`, otherwise return the second argument."""
375
+ return a if a is not None else b
376
+
377
+
378
+ @dataclasses.dataclass(frozen=True, slots=True)
379
+ class SafeGetItemProxy:
380
+ """Wrapper redirecting `__getitem__` to `get` with a sentinel value as default
381
+
382
+ This makes it safe to use in `operator.itemgetter` when some keys may be missing
383
+ """
384
+
385
+ wrapped: Mapping[str, Any]
386
+
387
+ def __getitem__(self, key: str, /) -> Any:
388
+ return self.wrapped.get(key, _SENTINEL)
389
+
390
+ # required to pass the object to operator.itemgetter() instances due to a quirk of typeshed
391
+ # https://github.com/python/mypy/issues/13713
392
+ # https://github.com/python/typeshed/pull/8785
393
+ # Since this is typing-only, hide it in a typing.TYPE_CHECKING block
394
+ if TYPE_CHECKING:
395
+
396
+ def __contains__(self, key: str, /) -> bool:
397
+ return self.wrapped.__contains__(key)
398
+
399
+
400
+ _ModelT = TypeVar('_ModelT', bound='BaseModel')
401
+ _RT = TypeVar('_RT')
402
+
403
+
404
+ class deprecated_instance_property(Generic[_ModelT, _RT]):
405
+ """A decorator exposing the decorated class method as a property, with a warning on instance access.
406
+
407
+ This decorator takes a class method defined on the `BaseModel` class and transforms it into
408
+ an attribute. The attribute can be accessed on both the class and instances of the class. If accessed
409
+ via an instance, a deprecation warning is emitted stating that instance access will be removed in V3.
410
+ """
411
+
412
+ def __init__(self, fget: Callable[[type[_ModelT]], _RT], /) -> None:
413
+ # Note: fget should be a classmethod:
414
+ self.fget = fget
415
+
416
+ @overload
417
+ def __get__(self, instance: None, objtype: type[_ModelT]) -> _RT: ...
418
+ @overload
419
+ @deprecated(
420
+ 'Accessing this attribute on the instance is deprecated, and will be removed in Pydantic V3. '
421
+ 'Instead, you should access this attribute from the model class.',
422
+ category=None,
423
+ )
424
+ def __get__(self, instance: _ModelT, objtype: type[_ModelT]) -> _RT: ...
425
+ def __get__(self, instance: _ModelT | None, objtype: type[_ModelT]) -> _RT:
426
+ if instance is not None:
427
+ warnings.warn(
428
+ f'Accessing the {self.fget.__name__!r} attribute on the instance is deprecated. '
429
+ 'Instead, you should access this attribute from the model class.',
430
+ category=PydanticDeprecatedSince211,
431
+ stacklevel=2,
432
+ )
433
+ return self.fget.__get__(instance, objtype)()
@@ -0,0 +1,141 @@
1
+ from __future__ import annotations as _annotations
2
+
3
+ import functools
4
+ import inspect
5
+ from collections.abc import Awaitable, Callable
6
+ from functools import partial
7
+ from typing import Any
8
+
9
+ import pydantic_core
10
+
11
+ from ..config import ConfigDict
12
+ from ..plugin._schema_validator import create_schema_validator
13
+ from ._config import ConfigWrapper
14
+ from ._generate_schema import GenerateSchema, ValidateCallSupportedTypes
15
+ from ._namespace_utils import MappingNamespace, NsResolver, ns_for_function
16
+ from ._typing_extra import signature_no_eval
17
+
18
+
19
+ def extract_function_name(func: ValidateCallSupportedTypes) -> str:
20
+ """Extract the name of a `ValidateCallSupportedTypes` object."""
21
+ return f'partial({func.func.__name__})' if isinstance(func, functools.partial) else func.__name__
22
+
23
+
24
+ def extract_function_qualname(func: ValidateCallSupportedTypes) -> str:
25
+ """Extract the qualname of a `ValidateCallSupportedTypes` object."""
26
+ return f'partial({func.func.__qualname__})' if isinstance(func, functools.partial) else func.__qualname__
27
+
28
+
29
+ def update_wrapper_attributes(wrapped: ValidateCallSupportedTypes, wrapper: Callable[..., Any]):
30
+ """Update the `wrapper` function with the attributes of the `wrapped` function. Return the updated function."""
31
+ if inspect.iscoroutinefunction(wrapped):
32
+
33
+ @functools.wraps(wrapped)
34
+ async def wrapper_function(*args, **kwargs): # type: ignore
35
+ return await wrapper(*args, **kwargs)
36
+ else:
37
+
38
+ @functools.wraps(wrapped)
39
+ def wrapper_function(*args, **kwargs):
40
+ return wrapper(*args, **kwargs)
41
+
42
+ # We need to manually update this because `partial` object has no `__name__` and `__qualname__`.
43
+ wrapper_function.__name__ = extract_function_name(wrapped)
44
+ wrapper_function.__qualname__ = extract_function_qualname(wrapped)
45
+ wrapper_function.raw_function = wrapped # type: ignore
46
+
47
+ return wrapper_function
48
+
49
+
50
+ class ValidateCallWrapper:
51
+ """This is a wrapper around a function that validates the arguments passed to it, and optionally the return value."""
52
+
53
+ __slots__ = (
54
+ 'function',
55
+ 'validate_return',
56
+ 'schema_type',
57
+ 'module',
58
+ 'qualname',
59
+ 'ns_resolver',
60
+ 'config_wrapper',
61
+ '__pydantic_complete__',
62
+ '__pydantic_validator__',
63
+ '__return_pydantic_validator__',
64
+ )
65
+
66
+ def __init__(
67
+ self,
68
+ function: ValidateCallSupportedTypes,
69
+ config: ConfigDict | None,
70
+ validate_return: bool,
71
+ parent_namespace: MappingNamespace | None,
72
+ ) -> None:
73
+ self.function = function
74
+ self.validate_return = validate_return
75
+ if isinstance(function, partial):
76
+ self.schema_type = function.func
77
+ self.module = function.func.__module__
78
+ else:
79
+ self.schema_type = function
80
+ self.module = function.__module__
81
+ self.qualname = extract_function_qualname(function)
82
+
83
+ self.ns_resolver = NsResolver(
84
+ namespaces_tuple=ns_for_function(self.schema_type, parent_namespace=parent_namespace)
85
+ )
86
+ self.config_wrapper = ConfigWrapper(config)
87
+ if not self.config_wrapper.defer_build:
88
+ self._create_validators()
89
+ else:
90
+ self.__pydantic_complete__ = False
91
+
92
+ def _create_validators(self) -> None:
93
+ gen_schema = GenerateSchema(self.config_wrapper, self.ns_resolver)
94
+ schema = gen_schema.clean_schema(gen_schema.generate_schema(self.function))
95
+ core_config = self.config_wrapper.core_config(title=self.qualname)
96
+
97
+ self.__pydantic_validator__ = create_schema_validator(
98
+ schema,
99
+ self.schema_type,
100
+ self.module,
101
+ self.qualname,
102
+ 'validate_call',
103
+ core_config,
104
+ self.config_wrapper.plugin_settings,
105
+ )
106
+ if self.validate_return:
107
+ signature = signature_no_eval(self.function)
108
+ return_type = signature.return_annotation if signature.return_annotation is not signature.empty else Any
109
+ gen_schema = GenerateSchema(self.config_wrapper, self.ns_resolver)
110
+ schema = gen_schema.clean_schema(gen_schema.generate_schema(return_type))
111
+ validator = create_schema_validator(
112
+ schema,
113
+ self.schema_type,
114
+ self.module,
115
+ self.qualname,
116
+ 'validate_call',
117
+ core_config,
118
+ self.config_wrapper.plugin_settings,
119
+ )
120
+ if inspect.iscoroutinefunction(self.function):
121
+
122
+ async def return_val_wrapper(aw: Awaitable[Any]) -> None:
123
+ return validator.validate_python(await aw)
124
+
125
+ self.__return_pydantic_validator__ = return_val_wrapper
126
+ else:
127
+ self.__return_pydantic_validator__ = validator.validate_python
128
+ else:
129
+ self.__return_pydantic_validator__ = None
130
+
131
+ self.__pydantic_complete__ = True
132
+
133
+ def __call__(self, /, *args: Any, **kwargs: Any) -> Any:
134
+ if not self.__pydantic_complete__:
135
+ self._create_validators()
136
+
137
+ res = self.__pydantic_validator__.validate_python(pydantic_core.ArgsKwargs(args, kwargs))
138
+ if self.__return_pydantic_validator__:
139
+ return self.__return_pydantic_validator__(res)
140
+ else:
141
+ return res