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.
- pboot_validator/__init__.py +461 -0
- pboot_validator/_internal/__init__.py +0 -0
- pboot_validator/_internal/_config.py +408 -0
- pboot_validator/_internal/_contextlib.py +84 -0
- pboot_validator/_internal/_core_metadata.py +97 -0
- pboot_validator/_internal/_core_utils.py +156 -0
- pboot_validator/_internal/_dataclasses.py +327 -0
- pboot_validator/_internal/_decorators.py +906 -0
- pboot_validator/_internal/_decorators_v1.py +174 -0
- pboot_validator/_internal/_discriminated_union.py +510 -0
- pboot_validator/_internal/_docs_extraction.py +128 -0
- pboot_validator/_internal/_fields.py +910 -0
- pboot_validator/_internal/_forward_ref.py +23 -0
- pboot_validator/_internal/_generate_schema.py +3053 -0
- pboot_validator/_internal/_generics.py +572 -0
- pboot_validator/_internal/_git.py +27 -0
- pboot_validator/_internal/_import_utils.py +20 -0
- pboot_validator/_internal/_known_annotated_metadata.py +412 -0
- pboot_validator/_internal/_mock_val_ser.py +241 -0
- pboot_validator/_internal/_model_construction.py +833 -0
- pboot_validator/_internal/_namespace_utils.py +300 -0
- pboot_validator/_internal/_repr.py +129 -0
- pboot_validator/_internal/_schema_gather.py +49 -0
- pboot_validator/_internal/_schema_generation_shared.py +126 -0
- pboot_validator/_internal/_serializers.py +59 -0
- pboot_validator/_internal/_signature.py +193 -0
- pboot_validator/_internal/_type_refs.py +128 -0
- pboot_validator/_internal/_typing_extra.py +506 -0
- pboot_validator/_internal/_utils.py +433 -0
- pboot_validator/_internal/_validate_call.py +141 -0
- pboot_validator/_internal/_validators.py +541 -0
- pboot_validator/_migration.py +317 -0
- pboot_validator/alias_generators.py +62 -0
- pboot_validator/aliases.py +136 -0
- pboot_validator/annotated_handlers.py +123 -0
- pboot_validator/class_validators.py +5 -0
- pboot_validator/color.py +605 -0
- pboot_validator/config.py +1295 -0
- pboot_validator/dataclasses.py +385 -0
- pboot_validator/datetime_parse.py +5 -0
- pboot_validator/decorator.py +5 -0
- pboot_validator/deprecated/__init__.py +0 -0
- pboot_validator/deprecated/class_validators.py +257 -0
- pboot_validator/deprecated/config.py +72 -0
- pboot_validator/deprecated/copy_internals.py +224 -0
- pboot_validator/deprecated/decorator.py +286 -0
- pboot_validator/deprecated/json.py +142 -0
- pboot_validator/deprecated/parse.py +81 -0
- pboot_validator/deprecated/tools.py +104 -0
- pboot_validator/env_settings.py +5 -0
- pboot_validator/error_wrappers.py +5 -0
- pboot_validator/errors.py +185 -0
- pboot_validator/experimental/__init__.py +1 -0
- pboot_validator/experimental/arguments_schema.py +44 -0
- pboot_validator/experimental/missing_sentinel.py +29 -0
- pboot_validator/experimental/pipeline.py +684 -0
- pboot_validator/fields.py +2065 -0
- pboot_validator/functional_serializers.py +461 -0
- pboot_validator/functional_validators.py +920 -0
- pboot_validator/generics.py +5 -0
- pboot_validator/json.py +5 -0
- pboot_validator/json_schema.py +3283 -0
- pboot_validator/main.py +1947 -0
- pboot_validator/mypy.py +1469 -0
- pboot_validator/networks.py +1417 -0
- pboot_validator/parse.py +5 -0
- pboot_validator/plugin/__init__.py +190 -0
- pboot_validator/plugin/_loader.py +56 -0
- pboot_validator/plugin/_schema_validator.py +152 -0
- pboot_validator/py.typed +0 -0
- pboot_validator/root_model.py +189 -0
- pboot_validator/schema.py +5 -0
- pboot_validator/tools.py +5 -0
- pboot_validator/type_adapter.py +780 -0
- pboot_validator/types.py +3405 -0
- pboot_validator/typing.py +5 -0
- pboot_validator/utils.py +5 -0
- pboot_validator/v1/__init__.py +131 -0
- pboot_validator/v1/_hypothesis_plugin.py +391 -0
- pboot_validator/v1/annotated_types.py +72 -0
- pboot_validator/v1/class_validators.py +361 -0
- pboot_validator/v1/color.py +494 -0
- pboot_validator/v1/config.py +191 -0
- pboot_validator/v1/dataclasses.py +503 -0
- pboot_validator/v1/datetime_parse.py +248 -0
- pboot_validator/v1/decorator.py +264 -0
- pboot_validator/v1/env_settings.py +350 -0
- pboot_validator/v1/error_wrappers.py +161 -0
- pboot_validator/v1/errors.py +646 -0
- pboot_validator/v1/fields.py +1253 -0
- pboot_validator/v1/generics.py +400 -0
- pboot_validator/v1/json.py +112 -0
- pboot_validator/v1/main.py +1130 -0
- pboot_validator/v1/mypy.py +950 -0
- pboot_validator/v1/networks.py +747 -0
- pboot_validator/v1/parse.py +66 -0
- pboot_validator/v1/py.typed +0 -0
- pboot_validator/v1/schema.py +1163 -0
- pboot_validator/v1/tools.py +92 -0
- pboot_validator/v1/types.py +1213 -0
- pboot_validator/v1/typing.py +627 -0
- pboot_validator/v1/utils.py +807 -0
- pboot_validator/v1/validators.py +768 -0
- pboot_validator/v1/version.py +38 -0
- pboot_validator/validate_call_decorator.py +121 -0
- pboot_validator/validators.py +5 -0
- pboot_validator/version.py +113 -0
- pboot_validator/warnings.py +130 -0
- pboot_validator-1.0.0.dist-info/METADATA +93 -0
- pboot_validator-1.0.0.dist-info/RECORD +112 -0
- pboot_validator-1.0.0.dist-info/WHEEL +4 -0
- pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from collections.abc import Callable, Generator, Iterator, Mapping
|
|
5
|
+
from functools import cached_property
|
|
6
|
+
from types import MappingProxyType
|
|
7
|
+
from typing import Any, NamedTuple, TypeAlias, TypeVar
|
|
8
|
+
|
|
9
|
+
from typing_extensions import ParamSpec, TypeAliasType, TypeVarTuple
|
|
10
|
+
|
|
11
|
+
from ._contextlib import contextmanager
|
|
12
|
+
|
|
13
|
+
GlobalsNamespace: TypeAlias = 'dict[str, Any]'
|
|
14
|
+
"""A global namespace.
|
|
15
|
+
|
|
16
|
+
In most cases, this is a reference to the `__dict__` attribute of a module.
|
|
17
|
+
This namespace type is expected as the `globals` argument during annotations evaluation.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
MappingNamespace: TypeAlias = Mapping[str, Any]
|
|
21
|
+
"""Any kind of namespace.
|
|
22
|
+
|
|
23
|
+
In most cases, this is a local namespace (e.g. the `__dict__` attribute of a class,
|
|
24
|
+
the [`f_locals`][frame.f_locals] attribute of a frame object, when dealing with types
|
|
25
|
+
defined inside functions).
|
|
26
|
+
This namespace type is expected as the `locals` argument during annotations evaluation.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
_TypeVarLike: TypeAlias = 'TypeVar | ParamSpec | TypeVarTuple'
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class NamespacesTuple(NamedTuple):
|
|
33
|
+
"""A tuple of globals and locals to be used during annotations evaluation.
|
|
34
|
+
|
|
35
|
+
This datastructure is defined as a named tuple so that it can easily be unpacked:
|
|
36
|
+
|
|
37
|
+
```python {lint="skip" test="skip"}
|
|
38
|
+
def eval_type(typ: type[Any], ns: NamespacesTuple) -> None:
|
|
39
|
+
return eval(typ, *ns)
|
|
40
|
+
```
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
globals: GlobalsNamespace
|
|
44
|
+
"""The namespace to be used as the `globals` argument during annotations evaluation."""
|
|
45
|
+
|
|
46
|
+
locals: MappingNamespace
|
|
47
|
+
"""The namespace to be used as the `locals` argument during annotations evaluation."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def get_module_ns_of(obj: Any) -> dict[str, Any]:
|
|
51
|
+
"""Get the namespace of the module where the object is defined.
|
|
52
|
+
|
|
53
|
+
Caution: this function does not return a copy of the module namespace, so the result
|
|
54
|
+
should not be mutated. The burden of enforcing this is on the caller.
|
|
55
|
+
"""
|
|
56
|
+
module_name = getattr(obj, '__module__', None)
|
|
57
|
+
if module_name:
|
|
58
|
+
try:
|
|
59
|
+
return sys.modules[module_name].__dict__
|
|
60
|
+
except KeyError:
|
|
61
|
+
# happens occasionally, see https://github.com/pydantic/pydantic/issues/2363
|
|
62
|
+
return {}
|
|
63
|
+
return {}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# Note that this class is almost identical to `collections.ChainMap`, but need to enforce
|
|
67
|
+
# immutable mappings here:
|
|
68
|
+
class LazyLocalNamespace(Mapping[str, Any]):
|
|
69
|
+
"""A lazily evaluated mapping, to be used as the `locals` argument during annotations evaluation.
|
|
70
|
+
|
|
71
|
+
While the [`eval`][eval] function expects a mapping as the `locals` argument, it only
|
|
72
|
+
performs `__getitem__` calls. The [`Mapping`][collections.abc.Mapping] abstract base class
|
|
73
|
+
is fully implemented only for type checking purposes.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
*namespaces: The namespaces to consider, in ascending order of priority.
|
|
77
|
+
|
|
78
|
+
Example:
|
|
79
|
+
```python {lint="skip" test="skip"}
|
|
80
|
+
ns = LazyLocalNamespace({'a': 1, 'b': 2}, {'a': 3})
|
|
81
|
+
ns['a']
|
|
82
|
+
#> 3
|
|
83
|
+
ns['b']
|
|
84
|
+
#> 2
|
|
85
|
+
```
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(self, *namespaces: MappingNamespace) -> None:
|
|
89
|
+
self._namespaces = namespaces
|
|
90
|
+
|
|
91
|
+
@cached_property
|
|
92
|
+
def data(self) -> dict[str, Any]:
|
|
93
|
+
# In rare scenarios, a race condition can happen when iterating over class namespaces (i.e. created with `var(SomeClass)`),
|
|
94
|
+
# if another thread accesses the type annotations for the first time (since 3.14, reading annotations can set attributes
|
|
95
|
+
# such as `__annotations_cache__` or `__annotate_func__` to the type).
|
|
96
|
+
return {
|
|
97
|
+
k: v for ns in self._namespaces for k, v in (ns.copy() if isinstance(ns, MappingProxyType) else ns).items()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
def __len__(self) -> int:
|
|
101
|
+
return len(self.data)
|
|
102
|
+
|
|
103
|
+
def __getitem__(self, key: str) -> Any:
|
|
104
|
+
return self.data[key]
|
|
105
|
+
|
|
106
|
+
def __contains__(self, key: object) -> bool:
|
|
107
|
+
return key in self.data
|
|
108
|
+
|
|
109
|
+
def __iter__(self) -> Iterator[str]:
|
|
110
|
+
return iter(self.data)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def ns_for_function(obj: Callable[..., Any], parent_namespace: MappingNamespace | None = None) -> NamespacesTuple:
|
|
114
|
+
"""Return the global and local namespaces to be used when evaluating annotations for the provided function.
|
|
115
|
+
|
|
116
|
+
The global namespace will be the `__dict__` attribute of the module the function was defined in.
|
|
117
|
+
The local namespace will contain the `__type_params__` introduced by PEP 695.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
obj: The object to use when building namespaces.
|
|
121
|
+
parent_namespace: Optional namespace to be added with the lowest priority in the local namespace.
|
|
122
|
+
If the passed function is a method, the `parent_namespace` will be the namespace of the class
|
|
123
|
+
the method is defined in. Thus, we also fetch type `__type_params__` from there (i.e. the
|
|
124
|
+
class-scoped type variables).
|
|
125
|
+
"""
|
|
126
|
+
locals_list: list[MappingNamespace] = []
|
|
127
|
+
if parent_namespace is not None:
|
|
128
|
+
locals_list.append(parent_namespace)
|
|
129
|
+
|
|
130
|
+
# Get the `__type_params__` attribute introduced by PEP 695.
|
|
131
|
+
# Note that the `typing._eval_type` function expects type params to be
|
|
132
|
+
# passed as a separate argument. However, internally, `_eval_type` calls
|
|
133
|
+
# `ForwardRef._evaluate` which will merge type params with the localns,
|
|
134
|
+
# essentially mimicking what we do here.
|
|
135
|
+
type_params: tuple[_TypeVarLike, ...] = getattr(obj, '__type_params__', ())
|
|
136
|
+
if parent_namespace is not None:
|
|
137
|
+
# We also fetch type params from the parent namespace. If present, it probably
|
|
138
|
+
# means the function was defined in a class. This is to support the following:
|
|
139
|
+
# https://github.com/python/cpython/issues/124089.
|
|
140
|
+
type_params += parent_namespace.get('__type_params__', ())
|
|
141
|
+
|
|
142
|
+
locals_list.append({t.__name__: t for t in type_params})
|
|
143
|
+
|
|
144
|
+
# What about short-circuiting to `obj.__globals__`?
|
|
145
|
+
globalns = get_module_ns_of(obj)
|
|
146
|
+
|
|
147
|
+
return NamespacesTuple(globalns, LazyLocalNamespace(*locals_list))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class NsResolver:
|
|
151
|
+
"""A class responsible for the namespaces resolving logic for annotations evaluation.
|
|
152
|
+
|
|
153
|
+
This class handles the namespace logic when evaluating annotations mainly for class objects.
|
|
154
|
+
|
|
155
|
+
It holds a stack of classes that are being inspected during the core schema building,
|
|
156
|
+
and the `types_namespace` property exposes the globals and locals to be used for
|
|
157
|
+
type annotation evaluation. Additionally -- if no class is present in the stack -- a
|
|
158
|
+
fallback globals and locals can be provided using the `namespaces_tuple` argument
|
|
159
|
+
(this is useful when generating a schema for a simple annotation, e.g. when using
|
|
160
|
+
`TypeAdapter`).
|
|
161
|
+
|
|
162
|
+
The namespace creation logic is unfortunately flawed in some cases, for backwards
|
|
163
|
+
compatibility reasons and to better support valid edge cases. See the description
|
|
164
|
+
for the `parent_namespace` argument and the example for more details.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
namespaces_tuple: The default globals and locals to use if no class is present
|
|
168
|
+
on the stack. This can be useful when using the `GenerateSchema` class
|
|
169
|
+
with `TypeAdapter`, where the "type" being analyzed is a simple annotation.
|
|
170
|
+
parent_namespace: An optional parent namespace that will be added to the locals
|
|
171
|
+
with the lowest priority. For a given class defined in a function, the locals
|
|
172
|
+
of this function are usually used as the parent namespace:
|
|
173
|
+
|
|
174
|
+
```python {lint="skip" test="skip"}
|
|
175
|
+
from pboot_validator import BaseModel
|
|
176
|
+
|
|
177
|
+
def func() -> None:
|
|
178
|
+
SomeType = int
|
|
179
|
+
|
|
180
|
+
class Model(BaseModel):
|
|
181
|
+
f: 'SomeType'
|
|
182
|
+
|
|
183
|
+
# when collecting fields, an namespace resolver instance will be created
|
|
184
|
+
# this way:
|
|
185
|
+
# ns_resolver = NsResolver(parent_namespace={'SomeType': SomeType})
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
For backwards compatibility reasons and to support valid edge cases, this parent
|
|
189
|
+
namespace will be used for *every* type being pushed to the stack. In the future,
|
|
190
|
+
we might want to be smarter by only doing so when the type being pushed is defined
|
|
191
|
+
in the same module as the parent namespace.
|
|
192
|
+
|
|
193
|
+
Example:
|
|
194
|
+
```python {lint="skip" test="skip"}
|
|
195
|
+
ns_resolver = NsResolver(
|
|
196
|
+
parent_namespace={'fallback': 1},
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
class Sub:
|
|
200
|
+
m: 'Model'
|
|
201
|
+
|
|
202
|
+
class Model:
|
|
203
|
+
some_local = 1
|
|
204
|
+
sub: Sub
|
|
205
|
+
|
|
206
|
+
ns_resolver = NsResolver()
|
|
207
|
+
|
|
208
|
+
# This is roughly what happens when we build a core schema for `Model`:
|
|
209
|
+
with ns_resolver.push(Model):
|
|
210
|
+
ns_resolver.types_namespace
|
|
211
|
+
#> NamespacesTuple({'Sub': Sub}, {'Model': Model, 'some_local': 1})
|
|
212
|
+
# First thing to notice here, the model being pushed is added to the locals.
|
|
213
|
+
# Because `NsResolver` is being used during the model definition, it is not
|
|
214
|
+
# yet added to the globals. This is useful when resolving self-referencing annotations.
|
|
215
|
+
|
|
216
|
+
with ns_resolver.push(Sub):
|
|
217
|
+
ns_resolver.types_namespace
|
|
218
|
+
#> NamespacesTuple({'Sub': Sub}, {'Sub': Sub, 'Model': Model})
|
|
219
|
+
# Second thing to notice: `Sub` is present in both the globals and locals.
|
|
220
|
+
# This is not an issue, just that as described above, the model being pushed
|
|
221
|
+
# is added to the locals, but it happens to be present in the globals as well
|
|
222
|
+
# because it is already defined.
|
|
223
|
+
# Third thing to notice: `Model` is also added in locals. This is a backwards
|
|
224
|
+
# compatibility workaround that allows for `Sub` to be able to resolve `'Model'`
|
|
225
|
+
# correctly (as otherwise models would have to be rebuilt even though this
|
|
226
|
+
# doesn't look necessary).
|
|
227
|
+
```
|
|
228
|
+
"""
|
|
229
|
+
|
|
230
|
+
def __init__(
|
|
231
|
+
self,
|
|
232
|
+
namespaces_tuple: NamespacesTuple | None = None,
|
|
233
|
+
parent_namespace: MappingNamespace | None = None,
|
|
234
|
+
) -> None:
|
|
235
|
+
self._base_ns_tuple = namespaces_tuple or NamespacesTuple({}, {})
|
|
236
|
+
self._parent_ns = parent_namespace
|
|
237
|
+
self._types_stack: list[type[Any] | TypeAliasType] = []
|
|
238
|
+
|
|
239
|
+
@cached_property
|
|
240
|
+
def types_namespace(self) -> NamespacesTuple:
|
|
241
|
+
"""The current global and local namespaces to be used for annotations evaluation."""
|
|
242
|
+
if not self._types_stack:
|
|
243
|
+
# TODO: should we merge the parent namespace here?
|
|
244
|
+
# This is relevant for TypeAdapter, where there are no types on the stack, and we might
|
|
245
|
+
# need access to the parent_ns. Right now, we sidestep this in `type_adapter.py` by passing
|
|
246
|
+
# locals to both parent_ns and the base_ns_tuple, but this is a bit hacky.
|
|
247
|
+
# we might consider something like:
|
|
248
|
+
# if self._parent_ns is not None:
|
|
249
|
+
# # Hacky workarounds, see class docstring:
|
|
250
|
+
# # An optional parent namespace that will be added to the locals with the lowest priority
|
|
251
|
+
# locals_list: list[MappingNamespace] = [self._parent_ns, self._base_ns_tuple.locals]
|
|
252
|
+
# return NamespacesTuple(self._base_ns_tuple.globals, LazyLocalNamespace(*locals_list))
|
|
253
|
+
return self._base_ns_tuple
|
|
254
|
+
|
|
255
|
+
typ = self._types_stack[-1]
|
|
256
|
+
|
|
257
|
+
globalns = get_module_ns_of(typ)
|
|
258
|
+
|
|
259
|
+
locals_list: list[MappingNamespace] = []
|
|
260
|
+
# Hacky workarounds, see class docstring:
|
|
261
|
+
# An optional parent namespace that will be added to the locals with the lowest priority
|
|
262
|
+
if self._parent_ns is not None:
|
|
263
|
+
locals_list.append(self._parent_ns)
|
|
264
|
+
if len(self._types_stack) > 1:
|
|
265
|
+
first_type = self._types_stack[0]
|
|
266
|
+
locals_list.append({first_type.__name__: first_type})
|
|
267
|
+
|
|
268
|
+
# Adding `__type_params__` *before* `vars(typ)`, as the latter takes priority
|
|
269
|
+
# (see https://github.com/python/cpython/pull/120272).
|
|
270
|
+
# TODO `typ.__type_params__` when we drop support for Python 3.11:
|
|
271
|
+
type_params: tuple[_TypeVarLike, ...] = getattr(typ, '__type_params__', ())
|
|
272
|
+
if type_params:
|
|
273
|
+
# Adding `__type_params__` is mostly useful for generic classes defined using
|
|
274
|
+
# PEP 695 syntax *and* using forward annotations (see the example in
|
|
275
|
+
# https://github.com/python/cpython/issues/114053). For TypeAliasType instances,
|
|
276
|
+
# it is way less common, but still required if using a string annotation in the alias
|
|
277
|
+
# value, e.g. `type A[T] = 'T'` (which is not necessary in most cases).
|
|
278
|
+
locals_list.append({t.__name__: t for t in type_params})
|
|
279
|
+
|
|
280
|
+
# TypeAliasType instances don't have a `__dict__` attribute, so the check
|
|
281
|
+
# is necessary:
|
|
282
|
+
if hasattr(typ, '__dict__'):
|
|
283
|
+
locals_list.append(vars(typ))
|
|
284
|
+
|
|
285
|
+
# The `len(self._types_stack) > 1` check above prevents this from being added twice:
|
|
286
|
+
locals_list.append({typ.__name__: typ})
|
|
287
|
+
|
|
288
|
+
return NamespacesTuple(globalns, LazyLocalNamespace(*locals_list))
|
|
289
|
+
|
|
290
|
+
@contextmanager
|
|
291
|
+
def push(self, typ: type[Any] | TypeAliasType, /) -> Generator[None]:
|
|
292
|
+
"""Push a type to the stack."""
|
|
293
|
+
self._types_stack.append(typ)
|
|
294
|
+
# Reset the cached property:
|
|
295
|
+
self.__dict__.pop('types_namespace', None)
|
|
296
|
+
try:
|
|
297
|
+
yield
|
|
298
|
+
finally:
|
|
299
|
+
self._types_stack.pop()
|
|
300
|
+
self.__dict__.pop('types_namespace', None)
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Tools to provide pretty/human-readable display of objects."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations as _annotations
|
|
4
|
+
|
|
5
|
+
import types
|
|
6
|
+
from collections.abc import Callable, Collection, Generator, Iterable
|
|
7
|
+
from typing import TYPE_CHECKING, Any, ForwardRef, TypeAlias, cast
|
|
8
|
+
|
|
9
|
+
import typing_extensions
|
|
10
|
+
from typing_inspection import typing_objects
|
|
11
|
+
from typing_inspection.introspection import is_union_origin
|
|
12
|
+
|
|
13
|
+
from . import _typing_extra
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
ReprArgs: TypeAlias = Iterable[tuple[str | None, Any]]
|
|
17
|
+
RichReprResult: TypeAlias = Iterable[Any | tuple[Any] | tuple[str, Any] | tuple[str, Any, Any]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PlainRepr(str):
|
|
21
|
+
"""String class where repr doesn't include quotes. Useful with Representation when you want to return a string
|
|
22
|
+
representation of something that is valid (or pseudo-valid) python.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __repr__(self) -> str:
|
|
26
|
+
return str(self)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Representation:
|
|
30
|
+
# Mixin to provide `__str__`, `__repr__`, and `__pretty__` and `__rich_repr__` methods.
|
|
31
|
+
# `__pretty__` is used by [devtools](https://python-devtools.helpmanual.io/).
|
|
32
|
+
# `__rich_repr__` is used by [rich](https://rich.readthedocs.io/en/stable/pretty.html).
|
|
33
|
+
# (this is not a docstring to avoid adding a docstring to classes which inherit from Representation)
|
|
34
|
+
|
|
35
|
+
__slots__ = ()
|
|
36
|
+
|
|
37
|
+
def __repr_args__(self) -> ReprArgs:
|
|
38
|
+
"""Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
|
|
39
|
+
|
|
40
|
+
Can either return:
|
|
41
|
+
* name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
|
|
42
|
+
* or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
|
|
43
|
+
"""
|
|
44
|
+
attrs_names = cast(Collection[str], self.__slots__)
|
|
45
|
+
if not attrs_names and hasattr(self, '__dict__'):
|
|
46
|
+
attrs_names = self.__dict__.keys()
|
|
47
|
+
attrs = ((s, getattr(self, s)) for s in attrs_names)
|
|
48
|
+
return [(a, v if v is not self else self.__repr_recursion__(v)) for a, v in attrs if v is not None]
|
|
49
|
+
|
|
50
|
+
def __repr_name__(self) -> str:
|
|
51
|
+
"""Name of the instance's class, used in __repr__."""
|
|
52
|
+
return self.__class__.__name__
|
|
53
|
+
|
|
54
|
+
def __repr_recursion__(self, object: Any) -> str:
|
|
55
|
+
"""Returns the string representation of a recursive object."""
|
|
56
|
+
# This is copied over from the stdlib `pprint` module:
|
|
57
|
+
return f'<Recursion on {type(object).__name__} with id={id(object)}>'
|
|
58
|
+
|
|
59
|
+
def __repr_str__(self, join_str: str) -> str:
|
|
60
|
+
return join_str.join(repr(v) if a is None else f'{a}={v!r}' for a, v in self.__repr_args__())
|
|
61
|
+
|
|
62
|
+
def __pretty__(self, fmt: Callable[[Any], Any], **kwargs: Any) -> Generator[Any]:
|
|
63
|
+
"""Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects."""
|
|
64
|
+
yield self.__repr_name__() + '('
|
|
65
|
+
yield 1
|
|
66
|
+
for name, value in self.__repr_args__():
|
|
67
|
+
if name is not None:
|
|
68
|
+
yield name + '='
|
|
69
|
+
yield fmt(value)
|
|
70
|
+
yield ','
|
|
71
|
+
yield 0
|
|
72
|
+
yield -1
|
|
73
|
+
yield ')'
|
|
74
|
+
|
|
75
|
+
def __rich_repr__(self) -> RichReprResult:
|
|
76
|
+
"""Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects."""
|
|
77
|
+
for name, field_repr in self.__repr_args__():
|
|
78
|
+
if name is None:
|
|
79
|
+
yield field_repr
|
|
80
|
+
else:
|
|
81
|
+
yield name, field_repr
|
|
82
|
+
|
|
83
|
+
def __str__(self) -> str:
|
|
84
|
+
return self.__repr_str__(' ')
|
|
85
|
+
|
|
86
|
+
def __repr__(self) -> str:
|
|
87
|
+
return f'{self.__repr_name__()}({self.__repr_str__(", ")})'
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def display_as_type(obj: Any) -> str:
|
|
91
|
+
"""Pretty representation of a type, should be as close as possible to the original type definition string.
|
|
92
|
+
|
|
93
|
+
Takes some logic from `typing._type_repr`.
|
|
94
|
+
"""
|
|
95
|
+
if isinstance(obj, (types.FunctionType, types.BuiltinFunctionType)):
|
|
96
|
+
return obj.__name__
|
|
97
|
+
elif obj is ...:
|
|
98
|
+
return '...'
|
|
99
|
+
elif isinstance(obj, Representation):
|
|
100
|
+
return repr(obj)
|
|
101
|
+
elif isinstance(obj, ForwardRef) or typing_objects.is_typealiastype(obj):
|
|
102
|
+
return str(obj)
|
|
103
|
+
|
|
104
|
+
if not isinstance(obj, (_typing_extra.typing_base, _typing_extra.WithArgsTypes, type)):
|
|
105
|
+
obj = obj.__class__
|
|
106
|
+
|
|
107
|
+
if is_union_origin(typing_extensions.get_origin(obj)):
|
|
108
|
+
args = ', '.join(map(display_as_type, typing_extensions.get_args(obj)))
|
|
109
|
+
return f'Union[{args}]'
|
|
110
|
+
elif isinstance(obj, _typing_extra.WithArgsTypes):
|
|
111
|
+
if typing_objects.is_literal(typing_extensions.get_origin(obj)):
|
|
112
|
+
args = ', '.join(map(repr, typing_extensions.get_args(obj)))
|
|
113
|
+
else:
|
|
114
|
+
args = ', '.join(map(_display_type_arg, typing_extensions.get_args(obj)))
|
|
115
|
+
try:
|
|
116
|
+
return f'{obj.__qualname__}[{args}]'
|
|
117
|
+
except AttributeError:
|
|
118
|
+
return str(obj).replace('typing.', '').replace('typing_extensions.', '') # handles TypeAliasType in 3.12
|
|
119
|
+
elif isinstance(obj, type):
|
|
120
|
+
return obj.__qualname__
|
|
121
|
+
else:
|
|
122
|
+
return repr(obj).replace('typing.', '').replace('typing_extensions.', '')
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _display_type_arg(arg: Any) -> str:
|
|
126
|
+
# The parameters of `Callable[[int, str], bool]` are given as a list:
|
|
127
|
+
if isinstance(arg, list):
|
|
128
|
+
return f'[{", ".join(map(display_as_type, arg))}]'
|
|
129
|
+
return display_as_type(arg)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TypedDict
|
|
4
|
+
|
|
5
|
+
from pydantic_core._pydantic_core import _schema_gather
|
|
6
|
+
from pydantic_core.core_schema import CoreSchema, DefinitionReferenceSchema
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
'GatherResult',
|
|
10
|
+
'MissingDefinitionError',
|
|
11
|
+
'gather_schemas_for_cleaning',
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
MissingDefinitionError = _schema_gather.MissingDefinitionError
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class GatherResult(TypedDict):
|
|
18
|
+
"""Schema traversing result."""
|
|
19
|
+
|
|
20
|
+
collected_references: dict[str, DefinitionReferenceSchema | None]
|
|
21
|
+
"""The collected definition references.
|
|
22
|
+
|
|
23
|
+
If a definition reference schema can be inlined, it means that there is
|
|
24
|
+
only one in the whole core schema. As such, it is stored as the value.
|
|
25
|
+
Otherwise, the value is set to `None`.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
deferred_discriminator_schemas: list[CoreSchema]
|
|
29
|
+
"""The list of core schemas having the discriminator application deferred."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def gather_schemas_for_cleaning(schema: CoreSchema, definitions: dict[str, CoreSchema]) -> GatherResult:
|
|
33
|
+
"""Traverse the core schema and definitions and return the necessary information for schema cleaning.
|
|
34
|
+
|
|
35
|
+
During the core schema traversing, any `'definition-ref'` schema is:
|
|
36
|
+
|
|
37
|
+
- Validated: the reference must point to an existing definition. If this is not the case, a
|
|
38
|
+
`MissingDefinitionError` exception is raised.
|
|
39
|
+
- Stored in the context: the actual reference is stored in the context. Depending on whether
|
|
40
|
+
the `'definition-ref'` schema is encountered more that once, the schema itself is also
|
|
41
|
+
saved in the context to be inlined (i.e. replaced by the definition it points to).
|
|
42
|
+
"""
|
|
43
|
+
collected_references, deferred_discriminator_schemas = _schema_gather.gather_schemas_for_cleaning(
|
|
44
|
+
schema, definitions
|
|
45
|
+
)
|
|
46
|
+
return {
|
|
47
|
+
'collected_references': collected_references,
|
|
48
|
+
'deferred_discriminator_schemas': deferred_discriminator_schemas,
|
|
49
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Types and utility functions used by various other internal tools."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
7
|
+
|
|
8
|
+
from pydantic_core import core_schema
|
|
9
|
+
|
|
10
|
+
from ..annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from ..json_schema import GenerateJsonSchema, JsonSchemaValue
|
|
14
|
+
from ._core_utils import CoreSchemaOrField
|
|
15
|
+
from ._generate_schema import GenerateSchema
|
|
16
|
+
from ._namespace_utils import NamespacesTuple
|
|
17
|
+
|
|
18
|
+
GetJsonSchemaFunction = Callable[[CoreSchemaOrField, GetJsonSchemaHandler], JsonSchemaValue]
|
|
19
|
+
HandlerOverride = Callable[[CoreSchemaOrField], JsonSchemaValue]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class GenerateJsonSchemaHandler(GetJsonSchemaHandler):
|
|
23
|
+
"""JsonSchemaHandler implementation that doesn't do ref unwrapping by default.
|
|
24
|
+
|
|
25
|
+
This is used for any Annotated metadata so that we don't end up with conflicting
|
|
26
|
+
modifications to the definition schema.
|
|
27
|
+
|
|
28
|
+
Used internally by Pydantic, please do not rely on this implementation.
|
|
29
|
+
See `GetJsonSchemaHandler` for the handler API.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, generate_json_schema: GenerateJsonSchema, handler_override: HandlerOverride | None) -> None:
|
|
33
|
+
self.generate_json_schema = generate_json_schema
|
|
34
|
+
self.handler = handler_override or generate_json_schema.generate_inner
|
|
35
|
+
self.mode = generate_json_schema.mode
|
|
36
|
+
|
|
37
|
+
def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue:
|
|
38
|
+
return self.handler(core_schema)
|
|
39
|
+
|
|
40
|
+
def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue) -> JsonSchemaValue:
|
|
41
|
+
"""Resolves `$ref` in the json schema.
|
|
42
|
+
|
|
43
|
+
This returns the input json schema if there is no `$ref` in json schema.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
maybe_ref_json_schema: The input json schema that may contains `$ref`.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
Resolved json schema.
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
LookupError: If it can't find the definition for `$ref`.
|
|
53
|
+
"""
|
|
54
|
+
if '$ref' not in maybe_ref_json_schema:
|
|
55
|
+
return maybe_ref_json_schema
|
|
56
|
+
ref = maybe_ref_json_schema['$ref']
|
|
57
|
+
json_schema = self.generate_json_schema.get_schema_from_definitions(ref)
|
|
58
|
+
if json_schema is None:
|
|
59
|
+
raise LookupError(
|
|
60
|
+
f'Could not find a ref for {ref}.'
|
|
61
|
+
' Maybe you tried to call resolve_ref_schema from within a recursive model?'
|
|
62
|
+
)
|
|
63
|
+
return json_schema
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class CallbackGetCoreSchemaHandler(GetCoreSchemaHandler):
|
|
67
|
+
"""Wrapper to use an arbitrary function as a `GetCoreSchemaHandler`.
|
|
68
|
+
|
|
69
|
+
Used internally by Pydantic, please do not rely on this implementation.
|
|
70
|
+
See `GetCoreSchemaHandler` for the handler API.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
handler: Callable[[Any], core_schema.CoreSchema],
|
|
76
|
+
generate_schema: GenerateSchema,
|
|
77
|
+
ref_mode: Literal['to-def', 'unpack'] = 'to-def',
|
|
78
|
+
) -> None:
|
|
79
|
+
self._handler = handler
|
|
80
|
+
self._generate_schema = generate_schema
|
|
81
|
+
self._ref_mode = ref_mode
|
|
82
|
+
|
|
83
|
+
def __call__(self, source_type: Any, /) -> core_schema.CoreSchema:
|
|
84
|
+
schema = self._handler(source_type)
|
|
85
|
+
if self._ref_mode == 'to-def':
|
|
86
|
+
ref = schema.get('ref')
|
|
87
|
+
if ref is not None:
|
|
88
|
+
return self._generate_schema.defs.create_definition_reference_schema(schema)
|
|
89
|
+
return schema
|
|
90
|
+
else: # ref_mode = 'unpack'
|
|
91
|
+
return self.resolve_ref_schema(schema)
|
|
92
|
+
|
|
93
|
+
def _get_types_namespace(self) -> NamespacesTuple:
|
|
94
|
+
return self._generate_schema._types_namespace
|
|
95
|
+
|
|
96
|
+
def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema:
|
|
97
|
+
return self._generate_schema.generate_schema(source_type)
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def field_name(self) -> str | None:
|
|
101
|
+
return self._generate_schema.field_name_stack.get()
|
|
102
|
+
|
|
103
|
+
def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema) -> core_schema.CoreSchema:
|
|
104
|
+
"""Resolves reference in the core schema.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
maybe_ref_schema: The input core schema that may contains reference.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
Resolved core schema.
|
|
111
|
+
|
|
112
|
+
Raises:
|
|
113
|
+
LookupError: If it can't find the definition for reference.
|
|
114
|
+
"""
|
|
115
|
+
if maybe_ref_schema['type'] == 'definition-ref':
|
|
116
|
+
ref = maybe_ref_schema['schema_ref']
|
|
117
|
+
definition = self._generate_schema.defs.get_schema_from_ref(ref)
|
|
118
|
+
if definition is None:
|
|
119
|
+
raise LookupError(
|
|
120
|
+
f'Could not find a ref for {ref}.'
|
|
121
|
+
' Maybe you tried to call resolve_ref_schema from within a recursive model?'
|
|
122
|
+
)
|
|
123
|
+
return definition
|
|
124
|
+
elif maybe_ref_schema['type'] == 'definitions':
|
|
125
|
+
return self.resolve_ref_schema(maybe_ref_schema['schema'])
|
|
126
|
+
return maybe_ref_schema
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import collections
|
|
4
|
+
import collections.abc
|
|
5
|
+
import typing
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from pydantic_core import PydanticOmit, core_schema
|
|
9
|
+
|
|
10
|
+
from ._typing_extra import is_namedtuple
|
|
11
|
+
|
|
12
|
+
SEQUENCE_ORIGIN_MAP: dict[Any, Any] = {
|
|
13
|
+
typing.Deque: collections.deque, # noqa: UP006
|
|
14
|
+
collections.deque: collections.deque,
|
|
15
|
+
list: list,
|
|
16
|
+
typing.List: list, # noqa: UP006
|
|
17
|
+
tuple: tuple,
|
|
18
|
+
typing.Tuple: tuple, # noqa: UP006
|
|
19
|
+
set: set,
|
|
20
|
+
typing.AbstractSet: set,
|
|
21
|
+
typing.Set: set, # noqa: UP006
|
|
22
|
+
frozenset: frozenset,
|
|
23
|
+
typing.FrozenSet: frozenset, # noqa: UP006
|
|
24
|
+
typing.Sequence: list,
|
|
25
|
+
typing.MutableSequence: list,
|
|
26
|
+
typing.MutableSet: set,
|
|
27
|
+
# this doesn't handle subclasses of these
|
|
28
|
+
# parametrized typing.Set creates one of these
|
|
29
|
+
collections.abc.MutableSet: set,
|
|
30
|
+
collections.abc.Set: frozenset,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def serialize_sequence_via_list(
|
|
35
|
+
v: Any, handler: core_schema.SerializerFunctionWrapHandler, info: core_schema.SerializationInfo
|
|
36
|
+
) -> Any:
|
|
37
|
+
items: list[Any] = []
|
|
38
|
+
|
|
39
|
+
value_type = type(v)
|
|
40
|
+
mapped_origin = SEQUENCE_ORIGIN_MAP.get(value_type)
|
|
41
|
+
if mapped_origin is None and not is_namedtuple(value_type):
|
|
42
|
+
# we shouldn't hit this branch, should probably add a serialization error or something
|
|
43
|
+
return v
|
|
44
|
+
|
|
45
|
+
for index, item in enumerate(v):
|
|
46
|
+
try:
|
|
47
|
+
item_v = handler(item, index)
|
|
48
|
+
except PydanticOmit: # noqa: PERF203
|
|
49
|
+
pass
|
|
50
|
+
else:
|
|
51
|
+
items.append(item_v)
|
|
52
|
+
|
|
53
|
+
if info.mode_is_json():
|
|
54
|
+
return items
|
|
55
|
+
elif mapped_origin is not None:
|
|
56
|
+
return mapped_origin(items)
|
|
57
|
+
else:
|
|
58
|
+
# named tuple: if some items were excluded, it can't be re-created
|
|
59
|
+
return value_type(*items) if len(items) == len(v) else tuple(items)
|