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,572 @@
1
+ from __future__ import annotations
2
+
3
+ import operator
4
+ import sys
5
+ import types
6
+ import typing
7
+ from collections import ChainMap
8
+ from collections.abc import Generator, Mapping
9
+ from contextvars import ContextVar
10
+ from functools import reduce
11
+ from itertools import zip_longest
12
+ from types import prepare_class
13
+ from typing import TYPE_CHECKING, Annotated, Any, TypedDict, TypeVar, cast
14
+ from weakref import WeakValueDictionary
15
+
16
+ import typing_extensions
17
+ from typing_inspection import typing_objects
18
+ from typing_inspection.introspection import is_union_origin
19
+
20
+ from . import _type_refs, _typing_extra
21
+ from ._contextlib import contextmanager
22
+ from ._forward_ref import PydanticRecursiveRef
23
+ from ._utils import all_identical, is_model_class
24
+
25
+ if TYPE_CHECKING:
26
+ from ..main import BaseModel
27
+
28
+ GenericTypesCacheKey = tuple[Any, Any, tuple[Any, ...]]
29
+
30
+ # Note: We want to remove LimitedDict, but to do this, we'd need to improve the handling of generics caching.
31
+ # Right now, to handle recursive generics, we some types must remain cached for brief periods without references.
32
+ # By chaining the WeakValuesDict with a LimitedDict, we have a way to retain caching for all types with references,
33
+ # while also retaining a limited number of types even without references. This is generally enough to build
34
+ # specific recursive generic models without losing required items out of the cache.
35
+
36
+ KT = TypeVar('KT')
37
+ VT = TypeVar('VT')
38
+ _LIMITED_DICT_SIZE = 100
39
+
40
+
41
+ class LimitedDict(dict[KT, VT]):
42
+ def __init__(self, size_limit: int = _LIMITED_DICT_SIZE) -> None:
43
+ self.size_limit = size_limit
44
+ super().__init__()
45
+
46
+ def __setitem__(self, key: KT, value: VT, /) -> None:
47
+ super().__setitem__(key, value)
48
+ if len(self) > self.size_limit:
49
+ excess = len(self) - self.size_limit + self.size_limit // 10
50
+ to_remove = list(self.keys())[:excess]
51
+ for k in to_remove:
52
+ del self[k]
53
+
54
+
55
+ # weak dictionaries allow the dynamically created parametrized versions of generic models to get collected
56
+ # once they are no longer referenced by the caller.
57
+ GenericTypesCache = WeakValueDictionary[GenericTypesCacheKey, 'type[BaseModel]']
58
+
59
+ if TYPE_CHECKING:
60
+
61
+ class DeepChainMap(ChainMap[KT, VT]): # type: ignore
62
+ ...
63
+
64
+ else:
65
+
66
+ class DeepChainMap(ChainMap):
67
+ """Variant of ChainMap that allows direct updates to inner scopes.
68
+
69
+ Taken from https://docs.python.org/3/library/collections.html#collections.ChainMap,
70
+ with some light modifications for this use case.
71
+ """
72
+
73
+ def clear(self) -> None:
74
+ for mapping in self.maps:
75
+ mapping.clear()
76
+
77
+ def __setitem__(self, key: KT, value: VT) -> None:
78
+ for mapping in self.maps:
79
+ mapping[key] = value
80
+
81
+ def __delitem__(self, key: KT) -> None:
82
+ hit = False
83
+ for mapping in self.maps:
84
+ if key in mapping:
85
+ del mapping[key]
86
+ hit = True
87
+ if not hit:
88
+ raise KeyError(key)
89
+
90
+
91
+ # Despite the fact that LimitedDict _seems_ no longer necessary, I'm very nervous to actually remove it
92
+ # and discover later on that we need to re-add all this infrastructure...
93
+ # _GENERIC_TYPES_CACHE = DeepChainMap(GenericTypesCache(), LimitedDict())
94
+
95
+ _GENERIC_TYPES_CACHE = GenericTypesCache()
96
+
97
+
98
+ class PydanticGenericMetadata(TypedDict):
99
+ origin: type[BaseModel] | None # analogous to typing._GenericAlias.__origin__
100
+ args: tuple[Any, ...] # analogous to typing._GenericAlias.__args__
101
+ parameters: tuple[TypeVar, ...] # analogous to typing.Generic.__parameters__
102
+
103
+
104
+ def create_generic_submodel(
105
+ model_name: str, origin: type[BaseModel], args: tuple[Any, ...], params: tuple[Any, ...]
106
+ ) -> type[BaseModel]:
107
+ """Dynamically create a submodel of a provided (generic) BaseModel.
108
+
109
+ This is used when producing concrete parametrizations of generic models. This function
110
+ only *creates* the new subclass; the schema/validators/serialization must be updated to
111
+ reflect a concrete parametrization elsewhere.
112
+
113
+ Args:
114
+ model_name: The name of the newly created model.
115
+ origin: The base class for the new model to inherit from.
116
+ args: A tuple of generic metadata arguments.
117
+ params: A tuple of generic metadata parameters.
118
+
119
+ Returns:
120
+ The created submodel.
121
+ """
122
+ model_module, called_globally = _get_caller_frame_info(depth=3)
123
+ # If parametrized at the module level, the parametrized class is registered in this module (see below).
124
+ # Its `__module__` must match. We fall back to the module of the origin for backwards compatibility reasons.
125
+ module = model_module if called_globally and model_module is not None else origin.__module__
126
+ namespace: dict[str, Any] = {'__module__': module}
127
+ # As per https://docs.python.org/3/reference/datamodel.html#slots:
128
+ # "The action of a __slots__ declaration is not limited to the class where it is defined.
129
+ # __slots__ declared in parents are available in child classes. However, instances of a
130
+ # child subclass will get a __dict__ and __weakref__ unless the subclass also defines
131
+ # __slots__".
132
+ # Because when users parameterize a generic model, we create a subclass of such generic model
133
+ # (what happens in this function), they can't control the fact that no slots is defined on the
134
+ # dynamic subclass, and so even if they defined extra __slots__ on the generic class (which results
135
+ # in the class *not* being weakref-able), the parameterized class *will* be weakref-able.
136
+ # For this reason (and to make Pydantic generic models behavior closer to generic aliases),
137
+ # we forward any slots from the origin:
138
+ if '__slots__' in origin.__dict__:
139
+ namespace['__slots__'] = origin.__dict__['__slots__']
140
+ bases = (origin,)
141
+ meta, ns, kwds = prepare_class(model_name, bases)
142
+ namespace.update(ns)
143
+ created_model = meta(
144
+ model_name,
145
+ bases,
146
+ namespace,
147
+ __pydantic_generic_metadata__={
148
+ 'origin': origin,
149
+ 'args': args,
150
+ 'parameters': params,
151
+ },
152
+ __pydantic_reset_parent_namespace__=False,
153
+ **kwds,
154
+ )
155
+
156
+ if called_globally: # create global reference and therefore allow pickling
157
+ object_by_reference = None
158
+ reference_name = model_name
159
+ reference_module_globals = sys.modules[module].__dict__
160
+ while object_by_reference is not created_model:
161
+ object_by_reference = reference_module_globals.setdefault(reference_name, created_model)
162
+ reference_name += '_'
163
+
164
+ return created_model
165
+
166
+
167
+ def _get_caller_frame_info(depth: int = 2) -> tuple[str | None, bool]:
168
+ """Used inside a function to check whether it was called globally.
169
+
170
+ Args:
171
+ depth: The depth to get the frame.
172
+
173
+ Returns:
174
+ A tuple contains `module_name` and `called_globally`.
175
+
176
+ Raises:
177
+ RuntimeError: If the function is not called inside a function.
178
+ """
179
+ try:
180
+ previous_caller_frame = sys._getframe(depth)
181
+ except ValueError as e:
182
+ raise RuntimeError('This function must be used inside another function') from e
183
+ except AttributeError: # sys module does not have _getframe function, so there's nothing we can do about it
184
+ return None, False
185
+ frame_globals = previous_caller_frame.f_globals
186
+ return frame_globals.get('__name__'), previous_caller_frame.f_locals is frame_globals
187
+
188
+
189
+ DictValues: type[Any] = {}.values().__class__
190
+
191
+
192
+ def iter_contained_typevars(v: Any) -> Generator[TypeVar]:
193
+ """Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found.
194
+
195
+ This is inspired as an alternative to directly accessing the `__parameters__` attribute of a GenericAlias,
196
+ since __parameters__ of (nested) generic BaseModel subclasses won't show up in that list.
197
+ """
198
+ if isinstance(v, TypeVar):
199
+ yield v
200
+ elif is_model_class(v):
201
+ yield from v.__pydantic_generic_metadata__['parameters']
202
+ elif isinstance(v, (DictValues, list)):
203
+ for var in v:
204
+ yield from iter_contained_typevars(var)
205
+ else:
206
+ args = get_args(v)
207
+ for arg in args:
208
+ yield from iter_contained_typevars(arg)
209
+
210
+
211
+ def get_args(v: Any) -> Any:
212
+ pydantic_generic_metadata: PydanticGenericMetadata | None = getattr(v, '__pydantic_generic_metadata__', None)
213
+ if pydantic_generic_metadata:
214
+ return pydantic_generic_metadata.get('args')
215
+ return typing_extensions.get_args(v)
216
+
217
+
218
+ def get_origin(v: Any) -> Any:
219
+ pydantic_generic_metadata: PydanticGenericMetadata | None = getattr(v, '__pydantic_generic_metadata__', None)
220
+ if pydantic_generic_metadata:
221
+ return pydantic_generic_metadata.get('origin')
222
+ return typing_extensions.get_origin(v)
223
+
224
+
225
+ def _map_type_parameters(target: Any, parameters: tuple[Any, ...], args: tuple[Any, ...]) -> dict[TypeVar, Any]:
226
+ """Return a mapping between the type parameters of `target` and the provided arguments.
227
+
228
+ Missing arguments are filled with the parameter's default (if any).
229
+
230
+ Raises:
231
+ TypeError: If the number of arguments does not match the parameters (i.e. if providing too few or too many arguments).
232
+
233
+ Note:
234
+ This function is analogous to the private `typing._check_generic_specialization` function.
235
+ """
236
+ expected_len = len(parameters)
237
+ typevars_map: dict[TypeVar, Any] = {}
238
+
239
+ _MISSING = typing_extensions.Sentinel('_MISSING')
240
+ for parameter, argument in zip_longest(parameters, args, fillvalue=_MISSING):
241
+ if parameter is _MISSING:
242
+ raise TypeError(f'Too many arguments for {target}; actual {len(args)}, expected {expected_len}')
243
+
244
+ if argument is _MISSING:
245
+ param = cast(TypeVar, parameter)
246
+ try:
247
+ has_default = param.has_default() # pyright: ignore[reportAttributeAccessIssue]
248
+ except AttributeError:
249
+ # Happens if using `typing.TypeVar` (and not `typing_extensions`) on Python < 3.13.
250
+ has_default = False
251
+ if has_default:
252
+ # The default might refer to other type parameters. For an example, see:
253
+ # https://typing.python.org/en/latest/spec/generics.html#type-parameters-as-parameters-to-generics
254
+ typevars_map[param] = replace_types(param.__default__, typevars_map) # pyright: ignore[reportAttributeAccessIssue]
255
+ else:
256
+ expected_len -= sum(hasattr(p, 'has_default') and p.has_default() for p in parameters) # pyright: ignore[reportAttributeAccessIssue]
257
+ raise TypeError(f'Too few arguments for {target}; actual {len(args)}, expected at least {expected_len}')
258
+ else:
259
+ param = cast(TypeVar, parameter)
260
+ typevars_map[param] = argument
261
+
262
+ return typevars_map
263
+
264
+
265
+ def get_standard_typevars_map(cls: Any) -> dict[TypeVar, Any] | None:
266
+ """Package a generic type's typevars and parametrization (if present) into a dictionary compatible with the
267
+ `replace_types` function. Specifically, this works with standard typing generics and typing._GenericAlias.
268
+ """
269
+ origin = get_origin(cls)
270
+ if origin is None:
271
+ return None
272
+ if not hasattr(origin, '__parameters__'):
273
+ return None
274
+
275
+ # In this case, we know that cls is a _GenericAlias, and origin is the generic type
276
+ # So it is safe to access cls.__args__ and origin.__parameters__
277
+ args: tuple[Any, ...] = cls.__args__ # type: ignore
278
+ parameters: tuple[TypeVar, ...] = origin.__parameters__
279
+ # Type parameter defaults are not always applied to `__args__` (e.g. for type aliases
280
+ # created with the `type` statement), so missing arguments are filled from the defaults:
281
+ return _map_type_parameters(origin, parameters, args)
282
+
283
+
284
+ def get_model_typevars_map(cls: type[BaseModel]) -> dict[TypeVar, Any]:
285
+ """Package a generic BaseModel's typevars and concrete parametrization (if present) into a dictionary compatible
286
+ with the `replace_types` function.
287
+
288
+ Since BaseModel.__class_getitem__ does not produce a typing._GenericAlias, and the BaseModel generic info is
289
+ stored in the __pydantic_generic_metadata__ attribute, we need special handling here.
290
+ """
291
+ # TODO: This could be unified with `get_standard_typevars_map` if we stored the generic metadata
292
+ # in the __origin__, __args__, and __parameters__ attributes of the model.
293
+ generic_metadata = cls.__pydantic_generic_metadata__
294
+ origin = generic_metadata['origin']
295
+ args = generic_metadata['args']
296
+ if not args:
297
+ # No need to go into `iter_contained_typevars`:
298
+ return {}
299
+ return dict(zip(iter_contained_typevars(origin), args, strict=True))
300
+
301
+
302
+ def replace_types(type_: Any, type_map: Mapping[TypeVar, Any] | None) -> Any:
303
+ """Return type with all occurrences of `type_map` keys recursively replaced with their values.
304
+
305
+ Args:
306
+ type_: The class or generic alias.
307
+ type_map: Mapping from `TypeVar` instance to concrete types.
308
+
309
+ Returns:
310
+ A new type representing the basic structure of `type_` with all
311
+ `typevar_map` keys recursively replaced.
312
+
313
+ Example:
314
+ ```python
315
+ from pboot_validator._internal._generics import replace_types
316
+
317
+ replace_types(tuple[str, list[str] | float], {str: int})
318
+ #> tuple[int, list[int] | float]
319
+ ```
320
+ """
321
+ if not type_map:
322
+ return type_
323
+
324
+ type_args = get_args(type_)
325
+ origin_type = get_origin(type_)
326
+
327
+ if typing_objects.is_annotated(origin_type):
328
+ annotated_type, *annotations = type_args
329
+ annotated_type = replace_types(annotated_type, type_map)
330
+ # TODO remove parentheses when we drop support for Python 3.10:
331
+ return Annotated[(annotated_type, *annotations)]
332
+
333
+ # Having type args is a good indicator that this is a typing special form
334
+ # instance or a generic alias of some sort.
335
+ if type_args:
336
+ resolved_type_args = tuple(replace_types(arg, type_map) for arg in type_args)
337
+ if all_identical(type_args, resolved_type_args):
338
+ # If all arguments are the same, there is no need to modify the
339
+ # type or create a new object at all
340
+ return type_
341
+
342
+ if (
343
+ origin_type is not None
344
+ and isinstance(type_, _typing_extra.typing_base)
345
+ and not isinstance(origin_type, _typing_extra.typing_base)
346
+ and getattr(type_, '_name', None) is not None
347
+ ):
348
+ # In python < 3.9 generic aliases don't exist so any of these like `list`,
349
+ # `type` or `collections.abc.Callable` need to be translated.
350
+ # See: https://www.python.org/dev/peps/pep-0585
351
+ origin_type = getattr(typing, type_._name)
352
+ assert origin_type is not None
353
+
354
+ if is_union_origin(origin_type):
355
+ if any(typing_objects.is_any(arg) for arg in resolved_type_args):
356
+ # `Any | T` ~ `Any`:
357
+ resolved_type_args = (Any,)
358
+ # `Never | T` ~ `T`:
359
+ resolved_type_args = tuple(
360
+ arg
361
+ for arg in resolved_type_args
362
+ if not (typing_objects.is_noreturn(arg) or typing_objects.is_never(arg))
363
+ )
364
+
365
+ # PEP-604 syntax (e.g. `list | str`) is represented with a types.UnionType object that does not
366
+ # implement `__getitem__()`. In Python 3.14+, `typing.Union` and `types.UnionType` are the same,
367
+ # and we instead rely on `typing.Union` as it implicitly converts string annotations to `ForwardRef`
368
+ # instances (this is to avoid type errors as per https://github.com/python/cpython/pull/105366).
369
+ if sys.version_info < (3, 14) and origin_type is types.UnionType:
370
+ return reduce(operator.or_, resolved_type_args)
371
+ # NotRequired[T] and Required[T] don't support tuple type resolved_type_args, hence the condition below
372
+ return origin_type[resolved_type_args[0] if len(resolved_type_args) == 1 else resolved_type_args]
373
+
374
+ # We handle pydantic generic models separately as they don't have the same
375
+ # semantics as "typing" classes or generic aliases
376
+
377
+ if not origin_type and is_model_class(type_):
378
+ parameters = type_.__pydantic_generic_metadata__['parameters']
379
+ if not parameters:
380
+ return type_
381
+ resolved_type_args = tuple(replace_types(t, type_map) for t in parameters)
382
+ if all_identical(parameters, resolved_type_args):
383
+ return type_
384
+ return type_[resolved_type_args]
385
+
386
+ # Handle special case for typehints that can have lists as arguments.
387
+ # `typing.Callable[[int, str], int]` is an example for this.
388
+ if isinstance(type_, list):
389
+ resolved_list = [replace_types(element, type_map) for element in type_]
390
+ if all_identical(type_, resolved_list):
391
+ return type_
392
+ return resolved_list
393
+
394
+ # If all else fails, we try to resolve the type directly and otherwise just
395
+ # return the input with no modifications.
396
+ return type_map.get(type_, type_)
397
+
398
+
399
+ def map_generic_model_arguments(cls: type[BaseModel], args: tuple[Any, ...]) -> dict[TypeVar, Any]:
400
+ """Return a mapping between the parameters of a generic model and the provided arguments during parameterization.
401
+
402
+ Raises:
403
+ TypeError: If the number of arguments does not match the parameters (i.e. if providing too few or too many arguments).
404
+
405
+ Example:
406
+ ```python {test="skip" lint="skip"}
407
+ class Model[T, U, V = int](BaseModel): ...
408
+
409
+ map_generic_model_arguments(Model, (str, bytes))
410
+ #> {T: str, U: bytes, V: int}
411
+
412
+ map_generic_model_arguments(Model, (str,))
413
+ #> TypeError: Too few arguments for <class '__main__.Model'>; actual 1, expected at least 2
414
+
415
+ map_generic_model_arguments(Model, (str, bytes, int, complex))
416
+ #> TypeError: Too many arguments for <class '__main__.Model'>; actual 4, expected 3
417
+ ```
418
+
419
+ Note:
420
+ This function is analogous to the private `typing._check_generic_specialization` function.
421
+ """
422
+ parameters = cls.__pydantic_generic_metadata__['parameters']
423
+ return _map_type_parameters(cls, parameters, args)
424
+
425
+
426
+ _generic_recursion_cache: ContextVar[set[str] | None] = ContextVar('_generic_recursion_cache', default=None)
427
+
428
+
429
+ @contextmanager
430
+ def generic_recursion_self_type(
431
+ origin: type[BaseModel], args: tuple[Any, ...]
432
+ ) -> Generator[PydanticRecursiveRef | None]:
433
+ """This contextmanager should be placed around the recursive calls used to build a generic type,
434
+ and accept as arguments the generic origin type and the type arguments being passed to it.
435
+
436
+ If the same origin and arguments are observed twice, it implies that a self-reference placeholder
437
+ can be used while building the core schema, and will produce a schema_ref that will be valid in the
438
+ final parent schema.
439
+ """
440
+ previously_seen_type_refs = _generic_recursion_cache.get()
441
+ if previously_seen_type_refs is None:
442
+ previously_seen_type_refs = set()
443
+ token = _generic_recursion_cache.set(previously_seen_type_refs)
444
+ else:
445
+ token = None
446
+
447
+ try:
448
+ type_ref = _type_refs.model_type_ref(origin, args_override=args)
449
+ if type_ref in previously_seen_type_refs:
450
+ self_type = PydanticRecursiveRef(type_ref=type_ref)
451
+ yield self_type
452
+ else:
453
+ previously_seen_type_refs.add(type_ref)
454
+ yield
455
+ previously_seen_type_refs.remove(type_ref)
456
+ finally:
457
+ if token:
458
+ _generic_recursion_cache.reset(token)
459
+
460
+
461
+ def recursively_defined_type_refs() -> set[str]:
462
+ visited = _generic_recursion_cache.get()
463
+ if not visited:
464
+ return set() # not in a generic recursion, so there are no types
465
+
466
+ return visited.copy() # don't allow modifications
467
+
468
+
469
+ def _generic_cache_get(key: GenericTypesCacheKey) -> type[BaseModel] | None:
470
+ try:
471
+ return _GENERIC_TYPES_CACHE.get(key)
472
+ except TypeError: # unhashable typevar values
473
+ return None
474
+
475
+
476
+ def _generic_cache_set(key: GenericTypesCacheKey, value: type[BaseModel]) -> None:
477
+ try:
478
+ _GENERIC_TYPES_CACHE[key] = value
479
+ except TypeError: # unhashable typevar values
480
+ pass
481
+
482
+
483
+ def get_cached_generic_type_early(parent: type[BaseModel], typevar_values: Any) -> type[BaseModel] | None:
484
+ """The use of a two-stage cache lookup approach was necessary to have the highest performance possible for
485
+ repeated calls to `__class_getitem__` on generic types (which may happen in tighter loops during runtime),
486
+ while still ensuring that certain alternative parametrizations ultimately resolve to the same type.
487
+
488
+ As a concrete example, this approach was necessary to make Model[List[T]][int] equal to Model[List[int]].
489
+ The approach could be modified to not use two different cache keys at different points, but the
490
+ _early_cache_key is optimized to be as quick to compute as possible (for repeated-access speed), and the
491
+ _late_cache_key is optimized to be as "correct" as possible, so that two types that will ultimately be the
492
+ same after resolving the type arguments will always produce cache hits.
493
+
494
+ If we wanted to move to only using a single cache key per type, we would either need to always use the
495
+ slower/more computationally intensive logic associated with _late_cache_key, or would need to accept
496
+ that Model[List[T]][int] is a different type than Model[List[T]][int]. Because we rely on subclass relationships
497
+ during validation, I think it is worthwhile to ensure that types that are functionally equivalent are actually
498
+ equal.
499
+ """
500
+ return _generic_cache_get(_early_cache_key(parent, typevar_values))
501
+
502
+
503
+ def get_cached_generic_type_late(
504
+ parent: type[BaseModel], typevar_values: Any, origin: type[BaseModel], args: tuple[Any, ...]
505
+ ) -> type[BaseModel] | None:
506
+ """See the docstring of `get_cached_generic_type_early` for more information about the two-stage cache lookup."""
507
+ cached = _generic_cache_get(_late_cache_key(origin, args, typevar_values))
508
+ if cached is not None:
509
+ set_cached_generic_type(parent, typevar_values, cached, origin, args)
510
+ return cached
511
+
512
+
513
+ def set_cached_generic_type(
514
+ parent: type[BaseModel],
515
+ typevar_values: tuple[Any, ...],
516
+ type_: type[BaseModel],
517
+ origin: type[BaseModel] | None = None,
518
+ args: tuple[Any, ...] | None = None,
519
+ ) -> None:
520
+ """See the docstring of `get_cached_generic_type_early` for more information about why items are cached with
521
+ two different keys.
522
+ """
523
+ _generic_cache_set(_early_cache_key(parent, typevar_values), type_)
524
+ if len(typevar_values) == 1:
525
+ _generic_cache_set(_early_cache_key(parent, typevar_values[0]), type_)
526
+ if origin and args:
527
+ _generic_cache_set(_late_cache_key(origin, args, typevar_values), type_)
528
+
529
+
530
+ def _union_orderings_key(typevar_values: Any) -> Any:
531
+ """This is intended to help differentiate between Union types with the same arguments in different order.
532
+
533
+ Thanks to caching internal to the `typing` module, it is not possible to distinguish between
534
+ List[Union[int, float]] and List[Union[float, int]] (and similarly for other "parent" origins besides List)
535
+ because `typing` considers Union[int, float] to be equal to Union[float, int].
536
+
537
+ However, you _can_ distinguish between (top-level) Union[int, float] vs. Union[float, int].
538
+ Because we parse items as the first Union type that is successful, we get slightly more consistent behavior
539
+ if we make an effort to distinguish the ordering of items in a union. It would be best if we could _always_
540
+ get the exact-correct order of items in the union, but that would require a change to the `typing` module itself.
541
+ (See https://github.com/python/cpython/issues/86483 for reference.)
542
+ """
543
+ if isinstance(typevar_values, tuple):
544
+ return tuple(_union_orderings_key(value) for value in typevar_values)
545
+ elif typing_objects.is_union(typing_extensions.get_origin(typevar_values)):
546
+ return get_args(typevar_values)
547
+ else:
548
+ return ()
549
+
550
+
551
+ def _early_cache_key(cls: type[BaseModel], typevar_values: Any) -> GenericTypesCacheKey:
552
+ """This is intended for minimal computational overhead during lookups of cached types.
553
+
554
+ Note that this is overly simplistic, and it's possible that two different cls/typevar_values
555
+ inputs would ultimately result in the same type being created in BaseModel.__class_getitem__.
556
+ To handle this, we have a fallback _late_cache_key that is checked later if the _early_cache_key
557
+ lookup fails, and should result in a cache hit _precisely_ when the inputs to __class_getitem__
558
+ would result in the same type.
559
+ """
560
+ return cls, typevar_values, _union_orderings_key(typevar_values)
561
+
562
+
563
+ def _late_cache_key(origin: type[BaseModel], args: tuple[Any, ...], typevar_values: Any) -> GenericTypesCacheKey:
564
+ """This is intended for use later in the process of creating a new type, when we have more information
565
+ about the exact args that will be passed. If it turns out that a different set of inputs to
566
+ __class_getitem__ resulted in the same inputs to the generic type creation process, we can still
567
+ return the cached type, and update the cache with the _early_cache_key as well.
568
+ """
569
+ # The _union_orderings_key is placed at the start here to ensure there cannot be a collision with an
570
+ # _early_cache_key, as that function will always produce a BaseModel subclass as the first item in the key,
571
+ # whereas this function will always produce a tuple as the first item in the key.
572
+ return _union_orderings_key(typevar_values), origin, args
@@ -0,0 +1,27 @@
1
+ """Git utilities, adopted from mypy's git utilities (https://github.com/python/mypy/blob/master/mypy/git.py)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+
9
+ def is_git_repo(dir: Path) -> bool:
10
+ """Is the given directory version-controlled with git?"""
11
+ return dir.joinpath('.git').exists()
12
+
13
+
14
+ def have_git() -> bool: # pragma: no cover
15
+ """Can we run the git executable?"""
16
+ try:
17
+ subprocess.check_output(['git', '--help'])
18
+ return True
19
+ except subprocess.CalledProcessError:
20
+ return False
21
+ except OSError:
22
+ return False
23
+
24
+
25
+ def git_revision(dir: Path) -> str:
26
+ """Get the SHA-1 of the HEAD of a git repository."""
27
+ return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=dir).decode('utf-8').strip()
@@ -0,0 +1,20 @@
1
+ from functools import cache
2
+ from typing import TYPE_CHECKING
3
+
4
+ if TYPE_CHECKING:
5
+ from pboot_validator import BaseModel
6
+ from pboot_validator.fields import FieldInfo
7
+
8
+
9
+ @cache
10
+ def import_cached_base_model() -> type['BaseModel']:
11
+ from pboot_validator import BaseModel
12
+
13
+ return BaseModel
14
+
15
+
16
+ @cache
17
+ def import_cached_field_info() -> type['FieldInfo']:
18
+ from pboot_validator.fields import FieldInfo
19
+
20
+ return FieldInfo