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,385 @@
|
|
|
1
|
+
"""Provide an enhanced dataclass that performs validation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations as _annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import functools
|
|
7
|
+
import sys
|
|
8
|
+
import types
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from typing import TYPE_CHECKING, Any, Generic, Literal, NoReturn, TypeGuard, TypeVar, overload
|
|
11
|
+
from warnings import warn
|
|
12
|
+
|
|
13
|
+
from typing_extensions import dataclass_transform
|
|
14
|
+
|
|
15
|
+
from ._internal import _config, _decorators, _mock_val_ser, _namespace_utils, _typing_extra
|
|
16
|
+
from ._internal import _dataclasses as _pydantic_dataclasses
|
|
17
|
+
from ._migration import getattr_migration
|
|
18
|
+
from .config import ConfigDict
|
|
19
|
+
from .errors import PydanticUserError
|
|
20
|
+
from .fields import Field, FieldInfo, PrivateAttr
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from ._internal._dataclasses import PydanticDataclass
|
|
24
|
+
from ._internal._namespace_utils import MappingNamespace
|
|
25
|
+
|
|
26
|
+
__all__ = 'dataclass', 'rebuild_dataclass'
|
|
27
|
+
|
|
28
|
+
_T = TypeVar('_T')
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
|
|
32
|
+
@overload
|
|
33
|
+
def dataclass(
|
|
34
|
+
*,
|
|
35
|
+
init: Literal[False] = False,
|
|
36
|
+
repr: bool = True,
|
|
37
|
+
eq: bool = True,
|
|
38
|
+
order: bool = False,
|
|
39
|
+
unsafe_hash: bool = False,
|
|
40
|
+
frozen: bool = False,
|
|
41
|
+
config: ConfigDict | type[object] | None = None,
|
|
42
|
+
validate_on_init: bool | None = None,
|
|
43
|
+
kw_only: bool = ...,
|
|
44
|
+
slots: bool = ...,
|
|
45
|
+
) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore
|
|
46
|
+
...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
|
|
50
|
+
@overload
|
|
51
|
+
def dataclass(
|
|
52
|
+
_cls: type[_T], # type: ignore
|
|
53
|
+
*,
|
|
54
|
+
init: Literal[False] = False,
|
|
55
|
+
repr: bool = True,
|
|
56
|
+
eq: bool = True,
|
|
57
|
+
order: bool = False,
|
|
58
|
+
unsafe_hash: bool = False,
|
|
59
|
+
frozen: bool | None = None,
|
|
60
|
+
config: ConfigDict | type[object] | None = None,
|
|
61
|
+
validate_on_init: bool | None = None,
|
|
62
|
+
kw_only: bool = ...,
|
|
63
|
+
slots: bool = ...,
|
|
64
|
+
) -> type[PydanticDataclass]: ...
|
|
65
|
+
@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
|
|
66
|
+
def dataclass(
|
|
67
|
+
_cls: type[_T] | None = None,
|
|
68
|
+
*,
|
|
69
|
+
init: Literal[False] = False,
|
|
70
|
+
repr: bool = True,
|
|
71
|
+
eq: bool = True,
|
|
72
|
+
order: bool = False,
|
|
73
|
+
unsafe_hash: bool = False,
|
|
74
|
+
frozen: bool | None = None,
|
|
75
|
+
config: ConfigDict | type[object] | None = None,
|
|
76
|
+
validate_on_init: bool | None = None,
|
|
77
|
+
kw_only: bool = False,
|
|
78
|
+
slots: bool = False,
|
|
79
|
+
) -> Callable[[type[_T]], type[PydanticDataclass]] | type[PydanticDataclass]:
|
|
80
|
+
"""!!! abstract "Usage Documentation"
|
|
81
|
+
[`dataclasses`](../concepts/dataclasses.md)
|
|
82
|
+
|
|
83
|
+
A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python `dataclass`,
|
|
84
|
+
but with added validation.
|
|
85
|
+
|
|
86
|
+
This decorator should be used similarly to the [`@dataclasses.dataclass`][dataclasses.dataclass] decorator.
|
|
87
|
+
|
|
88
|
+
A Pydantic dataclass validates its inputs like a `BaseModel` does. Its
|
|
89
|
+
[`ValidationError`][pydantic_core.ValidationError] includes each rejected value, while
|
|
90
|
+
[Logfire](../integrations/logfire.md) can retain the complete validation input and surrounding trace
|
|
91
|
+
context — see [Troubleshooting validation errors](../errors/troubleshooting.md).
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
_cls: The target `dataclass`.
|
|
95
|
+
init: Included for signature compatibility with `dataclasses.dataclass`, and is passed through to
|
|
96
|
+
`dataclasses.dataclass` when appropriate. If specified, must be set to `False`, as pydantic inserts its
|
|
97
|
+
own `__init__()` function.
|
|
98
|
+
repr: A boolean indicating whether to include the field in the `__repr__()` output.
|
|
99
|
+
eq: Determines if a `__eq__()` method should be generated for the class.
|
|
100
|
+
order: Determines if comparison magic methods should be generated, such as `__lt__()`, but not `__eq__()`.
|
|
101
|
+
unsafe_hash: Determines if a `__hash__()` method should be included in the class, as in `dataclasses.dataclass`.
|
|
102
|
+
frozen: Determines if the generated class should be a 'frozen' `dataclass`, which does not allow its
|
|
103
|
+
attributes to be modified after it has been initialized. If not set, the value from the provided `config` argument will be used (and will default to `False` otherwise).
|
|
104
|
+
config: The Pydantic config to use for the `dataclass`.
|
|
105
|
+
validate_on_init: A deprecated parameter included for backwards compatibility; in V2, all Pydantic dataclasses
|
|
106
|
+
are validated on init.
|
|
107
|
+
kw_only: Determines if `__init__()` method parameters must be specified by keyword only. Defaults to `False`.
|
|
108
|
+
slots: Determines if the generated class should be a 'slots' `dataclass`, which does not allow the addition of
|
|
109
|
+
new attributes after instantiation.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
A decorator that accepts a class as its argument and returns a Pydantic `dataclass`.
|
|
113
|
+
|
|
114
|
+
Raises:
|
|
115
|
+
AssertionError: Raised if `init` is not `False` or `validate_on_init` is `False`.
|
|
116
|
+
"""
|
|
117
|
+
assert init is False, 'pboot_validator.dataclasses.dataclass only supports init=False'
|
|
118
|
+
assert validate_on_init is not False, 'validate_on_init=False is no longer supported'
|
|
119
|
+
|
|
120
|
+
def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]:
|
|
121
|
+
"""Create a Pydantic dataclass from a regular dataclass.
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
cls: The class to create the Pydantic dataclass from.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
A Pydantic dataclass.
|
|
128
|
+
"""
|
|
129
|
+
from ._internal._utils import is_model_class
|
|
130
|
+
|
|
131
|
+
if is_model_class(cls):
|
|
132
|
+
raise PydanticUserError(
|
|
133
|
+
f'Cannot create a Pydantic dataclass from {cls.__name__} as it is already a Pydantic model',
|
|
134
|
+
code='dataclass-on-model',
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
original_cls = cls
|
|
138
|
+
|
|
139
|
+
# we warn on conflicting config specifications, but only if the class doesn't have a dataclass base
|
|
140
|
+
# because a dataclass base might provide a __pydantic_config__ attribute that we don't want to warn about
|
|
141
|
+
has_dataclass_base = any(dataclasses.is_dataclass(base) for base in cls.__bases__)
|
|
142
|
+
if not has_dataclass_base and config is not None and hasattr(cls, '__pydantic_config__'):
|
|
143
|
+
warn(
|
|
144
|
+
f'`config` is set via both the `dataclass` decorator and `__pydantic_config__` for dataclass {cls.__name__}. '
|
|
145
|
+
f'The `config` specification from `dataclass` decorator will take priority.',
|
|
146
|
+
category=UserWarning,
|
|
147
|
+
stacklevel=2,
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# if config is not explicitly provided, try to read it from the type
|
|
151
|
+
config_dict = config if config is not None else getattr(cls, '__pydantic_config__', None)
|
|
152
|
+
config_wrapper = _config.ConfigWrapper(config_dict)
|
|
153
|
+
decorators = _decorators.DecoratorInfos.build(cls, replace_wrapped_methods=True)
|
|
154
|
+
decorators.update_from_config(config_wrapper)
|
|
155
|
+
|
|
156
|
+
# Keep track of the original __doc__ so that we can restore it after applying the dataclasses decorator
|
|
157
|
+
# Otherwise, classes with no __doc__ will have their signature added into the JSON schema description,
|
|
158
|
+
# since dataclasses.dataclass will set this as the __doc__
|
|
159
|
+
original_doc = cls.__doc__
|
|
160
|
+
|
|
161
|
+
if _pydantic_dataclasses.is_stdlib_dataclass(cls):
|
|
162
|
+
# Vanilla dataclasses include a default docstring (representing the class signature),
|
|
163
|
+
# which we don't want to preserve.
|
|
164
|
+
original_doc = None
|
|
165
|
+
|
|
166
|
+
# We don't want to add validation to the existing std lib dataclass, so we will subclass it
|
|
167
|
+
# If the class is generic, we need to make sure the subclass also inherits from Generic
|
|
168
|
+
# with all the same parameters.
|
|
169
|
+
bases = (cls,)
|
|
170
|
+
if issubclass(cls, Generic):
|
|
171
|
+
generic_base = Generic[cls.__parameters__] # type: ignore
|
|
172
|
+
bases = bases + (generic_base,)
|
|
173
|
+
cls = types.new_class(cls.__name__, bases)
|
|
174
|
+
|
|
175
|
+
# Respect frozen setting from dataclass constructor and fallback to config setting if not provided
|
|
176
|
+
if frozen is not None:
|
|
177
|
+
frozen_ = frozen
|
|
178
|
+
if config_wrapper.frozen:
|
|
179
|
+
# It's not recommended to define both, as the setting from the dataclass decorator will take priority.
|
|
180
|
+
warn(
|
|
181
|
+
f'`frozen` is set via both the `dataclass` decorator and `config` for dataclass {cls.__name__!r}.'
|
|
182
|
+
'This is not recommended. The `frozen` specification on `dataclass` will take priority.',
|
|
183
|
+
category=UserWarning,
|
|
184
|
+
stacklevel=2,
|
|
185
|
+
)
|
|
186
|
+
else:
|
|
187
|
+
frozen_ = config_wrapper.frozen or False
|
|
188
|
+
|
|
189
|
+
# Make Pydantic's `Field()` function compatible with stdlib dataclasses. As we'll decorate
|
|
190
|
+
# `cls` with the stdlib `@dataclass` decorator first, some attributes (`kw_only`, `repr`, `init`)
|
|
191
|
+
# need to be understood *during* the stdlib creation. We do so in two steps:
|
|
192
|
+
|
|
193
|
+
# 1. On the decorated class, wrap `Field()` assignment with `dataclass.field()`, with these
|
|
194
|
+
# attributes set (done in `as_dataclass_field()`)
|
|
195
|
+
cls_anns = _typing_extra.safe_get_annotations(cls)
|
|
196
|
+
for field_name in cls_anns:
|
|
197
|
+
# We should look for assignments in `__dict__` instead, but for now we follow
|
|
198
|
+
# the same behavior as stdlib dataclasses (see https://github.com/python/cpython/issues/88609)
|
|
199
|
+
field_value = getattr(cls, field_name, None)
|
|
200
|
+
if isinstance(field_value, FieldInfo):
|
|
201
|
+
setattr(cls, field_name, _pydantic_dataclasses.as_dataclass_field(field_value))
|
|
202
|
+
|
|
203
|
+
# 2. For bases of `cls` that are stdlib dataclasses, we temporarily patch their fields
|
|
204
|
+
# (see the docstring of the context manager):
|
|
205
|
+
with _pydantic_dataclasses.patch_base_fields(cls):
|
|
206
|
+
cls = dataclasses.dataclass( # pyright: ignore[reportCallIssue]
|
|
207
|
+
cls,
|
|
208
|
+
# the value of init here doesn't affect anything except that it makes it easier to generate a signature
|
|
209
|
+
init=True,
|
|
210
|
+
repr=repr,
|
|
211
|
+
eq=eq,
|
|
212
|
+
order=order,
|
|
213
|
+
unsafe_hash=unsafe_hash,
|
|
214
|
+
frozen=frozen_,
|
|
215
|
+
kw_only=kw_only,
|
|
216
|
+
slots=slots,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
if config_wrapper.validate_assignment:
|
|
220
|
+
original_setattr = cls.__setattr__
|
|
221
|
+
|
|
222
|
+
@functools.wraps(cls.__setattr__)
|
|
223
|
+
def validated_setattr(instance: PydanticDataclass, name: str, value: Any, /) -> None:
|
|
224
|
+
if frozen_:
|
|
225
|
+
return original_setattr(instance, name, value) # pyright: ignore[reportCallIssue]
|
|
226
|
+
inst_cls = type(instance)
|
|
227
|
+
attr = getattr(inst_cls, name, None)
|
|
228
|
+
|
|
229
|
+
if isinstance(attr, property):
|
|
230
|
+
attr.__set__(instance, value)
|
|
231
|
+
elif isinstance(attr, functools.cached_property):
|
|
232
|
+
instance.__dict__.__setitem__(name, value)
|
|
233
|
+
else:
|
|
234
|
+
inst_cls.__pydantic_validator__.validate_assignment(instance, name, value)
|
|
235
|
+
|
|
236
|
+
cls.__setattr__ = validated_setattr.__get__(None, cls) # type: ignore
|
|
237
|
+
|
|
238
|
+
if slots and not hasattr(cls, '__setstate__'):
|
|
239
|
+
# If slots is set, `pickle` (relied on by `copy.copy()`) will use
|
|
240
|
+
# `__setattr__()` to reconstruct the dataclass. However, the custom
|
|
241
|
+
# `__setattr__()` set above relies on `validate_assignment()`, which
|
|
242
|
+
# in turn expects all the field values to be already present on the
|
|
243
|
+
# instance, resulting in attribute errors.
|
|
244
|
+
# As such, we make use of `object.__setattr__()` instead.
|
|
245
|
+
# Note that we do so only if `__setstate__()` isn't already set (this is the
|
|
246
|
+
# case if on top of `slots`, `frozen` is used).
|
|
247
|
+
|
|
248
|
+
# Taken from `dataclasses._dataclass_get/setstate()`:
|
|
249
|
+
def _dataclass_getstate(self: Any) -> list[Any]:
|
|
250
|
+
return [getattr(self, f.name) for f in dataclasses.fields(self)]
|
|
251
|
+
|
|
252
|
+
def _dataclass_setstate(self: Any, state: list[Any]) -> None:
|
|
253
|
+
for field, value in zip(dataclasses.fields(self), state, strict=True):
|
|
254
|
+
object.__setattr__(self, field.name, value)
|
|
255
|
+
|
|
256
|
+
cls.__getstate__ = _dataclass_getstate # pyright: ignore[reportAttributeAccessIssue]
|
|
257
|
+
cls.__setstate__ = _dataclass_setstate # pyright: ignore[reportAttributeAccessIssue]
|
|
258
|
+
|
|
259
|
+
# This is an undocumented attribute to distinguish stdlib/Pydantic dataclasses.
|
|
260
|
+
# It should be set as early as possible:
|
|
261
|
+
cls.__is_pydantic_dataclass__ = True
|
|
262
|
+
cls.__pydantic_decorators__ = decorators # type: ignore
|
|
263
|
+
cls.__doc__ = original_doc
|
|
264
|
+
# Can be non-existent for dynamically created classes:
|
|
265
|
+
firstlineno = getattr(original_cls, '__firstlineno__', None)
|
|
266
|
+
cls.__module__ = original_cls.__module__
|
|
267
|
+
if sys.version_info >= (3, 13) and firstlineno is not None:
|
|
268
|
+
# As per https://docs.python.org/3/reference/datamodel.html#type.__firstlineno__:
|
|
269
|
+
# Setting the `__module__` attribute removes the `__firstlineno__` item from the type’s dictionary.
|
|
270
|
+
original_cls.__firstlineno__ = firstlineno
|
|
271
|
+
cls.__firstlineno__ = firstlineno
|
|
272
|
+
cls.__qualname__ = original_cls.__qualname__
|
|
273
|
+
cls.__pydantic_fields_complete__ = classmethod(_pydantic_fields_complete)
|
|
274
|
+
cls.__pydantic_complete__ = False # `complete_dataclass` will set it to `True` if successful.
|
|
275
|
+
# TODO `parent_namespace` is currently None, but we could do the same thing as Pydantic models:
|
|
276
|
+
# fetch the parent ns using `parent_frame_namespace` (if the dataclass was defined in a function),
|
|
277
|
+
# and possibly cache it (see the `__pydantic_parent_namespace__` logic for models).
|
|
278
|
+
_pydantic_dataclasses.complete_dataclass(cls, config_wrapper, raise_errors=False)
|
|
279
|
+
return cls
|
|
280
|
+
|
|
281
|
+
return create_dataclass if _cls is None else create_dataclass(_cls)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _pydantic_fields_complete(cls: type[PydanticDataclass]) -> bool:
|
|
285
|
+
"""Return whether the fields were successfully collected (i.e. type hints were successfully resolved).
|
|
286
|
+
|
|
287
|
+
This is a private helper, not meant to be used outside Pydantic.
|
|
288
|
+
"""
|
|
289
|
+
return all(field_info._complete for field_info in cls.__pydantic_fields__.values())
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
__getattr__ = getattr_migration(__name__)
|
|
293
|
+
|
|
294
|
+
if sys.version_info < (3, 11):
|
|
295
|
+
# Monkeypatch dataclasses.InitVar so that typing doesn't error if it occurs as a type when evaluating type hints
|
|
296
|
+
# Starting in 3.11, typing.get_type_hints will not raise an error if the retrieved type hints are not callable.
|
|
297
|
+
|
|
298
|
+
def _call_initvar(*args: Any, **kwargs: Any) -> NoReturn:
|
|
299
|
+
"""This function does nothing but raise an error that is as similar as possible to what you'd get
|
|
300
|
+
if you were to try calling `InitVar[int]()` without this monkeypatch. The whole purpose is just
|
|
301
|
+
to ensure typing._type_check does not error if the type hint evaluates to `InitVar[<parameter>]`.
|
|
302
|
+
"""
|
|
303
|
+
raise TypeError("'InitVar' object is not callable")
|
|
304
|
+
|
|
305
|
+
dataclasses.InitVar.__call__ = _call_initvar
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def rebuild_dataclass(
|
|
309
|
+
cls: type[PydanticDataclass],
|
|
310
|
+
*,
|
|
311
|
+
force: bool = False,
|
|
312
|
+
raise_errors: bool = True,
|
|
313
|
+
_parent_namespace_depth: int = 2,
|
|
314
|
+
_types_namespace: MappingNamespace | None = None,
|
|
315
|
+
) -> bool | None:
|
|
316
|
+
"""Try to rebuild the pydantic-core schema for the dataclass.
|
|
317
|
+
|
|
318
|
+
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
|
|
319
|
+
the initial attempt to build the schema, and automatic rebuilding fails.
|
|
320
|
+
|
|
321
|
+
This is analogous to `BaseModel.model_rebuild`.
|
|
322
|
+
|
|
323
|
+
Args:
|
|
324
|
+
cls: The class to rebuild the pydantic-core schema for.
|
|
325
|
+
force: Whether to force the rebuilding of the schema, defaults to `False`.
|
|
326
|
+
raise_errors: Whether to raise errors, defaults to `True`.
|
|
327
|
+
_parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
|
|
328
|
+
_types_namespace: The types namespace, defaults to `None`.
|
|
329
|
+
|
|
330
|
+
Returns:
|
|
331
|
+
Returns `None` if the schema is already "complete" and rebuilding was not required.
|
|
332
|
+
If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
|
333
|
+
"""
|
|
334
|
+
if not force and cls.__pydantic_complete__:
|
|
335
|
+
return None
|
|
336
|
+
|
|
337
|
+
for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
|
|
338
|
+
if attr in cls.__dict__ and not isinstance(
|
|
339
|
+
getattr(cls, attr), (_mock_val_ser.MockCoreSchema, _mock_val_ser.MockValSer)
|
|
340
|
+
):
|
|
341
|
+
# Deleting the validator/serializer is necessary as otherwise they can get reused in
|
|
342
|
+
# pydantic-core. Same applies for the core schema that can be reused in schema generation.
|
|
343
|
+
# We do so only if they aren't mock instances, otherwise concurrent reads of these attributes
|
|
344
|
+
# (e.g. when instantiating the dataclass in another thread) can resolve them from the parent class.
|
|
345
|
+
delattr(cls, attr)
|
|
346
|
+
|
|
347
|
+
cls.__pydantic_complete__ = False
|
|
348
|
+
|
|
349
|
+
if _types_namespace is not None:
|
|
350
|
+
rebuild_ns = _types_namespace
|
|
351
|
+
elif _parent_namespace_depth > 0:
|
|
352
|
+
rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
|
|
353
|
+
else:
|
|
354
|
+
rebuild_ns = {}
|
|
355
|
+
|
|
356
|
+
ns_resolver = _namespace_utils.NsResolver(
|
|
357
|
+
parent_namespace=rebuild_ns,
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
return _pydantic_dataclasses.complete_dataclass(
|
|
361
|
+
cls,
|
|
362
|
+
_config.ConfigWrapper(cls.__pydantic_config__, check=False),
|
|
363
|
+
raise_errors=raise_errors,
|
|
364
|
+
ns_resolver=ns_resolver,
|
|
365
|
+
# We could provide a different config instead (with `'defer_build'` set to `True`)
|
|
366
|
+
# of this explicit `_force_build` argument, but because config can come from the
|
|
367
|
+
# decorator parameter or the `__pydantic_config__` attribute, `complete_dataclass`
|
|
368
|
+
# will overwrite `__pydantic_config__` with the provided config above:
|
|
369
|
+
_force_build=True,
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def is_pydantic_dataclass(class_: type[Any], /) -> TypeGuard[type[PydanticDataclass]]:
|
|
374
|
+
"""Whether a class is a pydantic dataclass.
|
|
375
|
+
|
|
376
|
+
Args:
|
|
377
|
+
class_: The class.
|
|
378
|
+
|
|
379
|
+
Returns:
|
|
380
|
+
`True` if the class is a pydantic dataclass, `False` otherwise.
|
|
381
|
+
"""
|
|
382
|
+
try:
|
|
383
|
+
return '__is_pydantic_dataclass__' in class_.__dict__ and dataclasses.is_dataclass(class_)
|
|
384
|
+
except AttributeError:
|
|
385
|
+
return False
|
|
File without changes
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Old `@validator` and `@root_validator` function validators from V1."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations as _annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from functools import partial, partialmethod
|
|
7
|
+
from types import FunctionType
|
|
8
|
+
from typing import TYPE_CHECKING, Any, Literal, TypeAlias, TypeVar, Union, overload
|
|
9
|
+
from warnings import warn
|
|
10
|
+
|
|
11
|
+
from typing_extensions import Protocol, deprecated
|
|
12
|
+
|
|
13
|
+
from .._internal import _decorators, _decorators_v1
|
|
14
|
+
from ..errors import PydanticUserError
|
|
15
|
+
from ..warnings import PydanticDeprecatedSince20
|
|
16
|
+
|
|
17
|
+
_ALLOW_REUSE_WARNING_MESSAGE = '`allow_reuse` is deprecated and will be ignored; it should no longer be necessary'
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
|
|
22
|
+
class _OnlyValueValidatorClsMethod(Protocol):
|
|
23
|
+
def __call__(self, __cls: Any, __value: Any) -> Any: ...
|
|
24
|
+
|
|
25
|
+
class _V1ValidatorWithValuesClsMethod(Protocol):
|
|
26
|
+
def __call__(self, __cls: Any, __value: Any, values: dict[str, Any]) -> Any: ...
|
|
27
|
+
|
|
28
|
+
class _V1ValidatorWithValuesKwOnlyClsMethod(Protocol):
|
|
29
|
+
def __call__(self, __cls: Any, __value: Any, *, values: dict[str, Any]) -> Any: ...
|
|
30
|
+
|
|
31
|
+
class _V1ValidatorWithKwargsClsMethod(Protocol):
|
|
32
|
+
def __call__(self, __cls: Any, **kwargs: Any) -> Any: ...
|
|
33
|
+
|
|
34
|
+
class _V1ValidatorWithValuesAndKwargsClsMethod(Protocol):
|
|
35
|
+
def __call__(self, __cls: Any, values: dict[str, Any], **kwargs: Any) -> Any: ...
|
|
36
|
+
|
|
37
|
+
class _V1RootValidatorClsMethod(Protocol):
|
|
38
|
+
def __call__(
|
|
39
|
+
self, __cls: Any, __values: _decorators_v1.RootValidatorValues
|
|
40
|
+
) -> _decorators_v1.RootValidatorValues: ...
|
|
41
|
+
|
|
42
|
+
V1Validator = Union[
|
|
43
|
+
_OnlyValueValidatorClsMethod,
|
|
44
|
+
_V1ValidatorWithValuesClsMethod,
|
|
45
|
+
_V1ValidatorWithValuesKwOnlyClsMethod,
|
|
46
|
+
_V1ValidatorWithKwargsClsMethod,
|
|
47
|
+
_V1ValidatorWithValuesAndKwargsClsMethod,
|
|
48
|
+
_decorators_v1.V1ValidatorWithValues,
|
|
49
|
+
_decorators_v1.V1ValidatorWithValuesKwOnly,
|
|
50
|
+
_decorators_v1.V1ValidatorWithKwargs,
|
|
51
|
+
_decorators_v1.V1ValidatorWithValuesAndKwargs,
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
V1RootValidator = Union[
|
|
55
|
+
_V1RootValidatorClsMethod,
|
|
56
|
+
_decorators_v1.V1RootValidatorFunction,
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
_PartialClsOrStaticMethod: TypeAlias = classmethod[Any, Any, Any] | staticmethod[Any, Any] | partialmethod[Any]
|
|
60
|
+
|
|
61
|
+
# Allow both a V1 (assumed pre=False) or V2 (assumed mode='after') validator
|
|
62
|
+
# We lie to type checkers and say we return the same thing we get
|
|
63
|
+
# but in reality we return a proxy object that _mostly_ behaves like the wrapped thing
|
|
64
|
+
_V1ValidatorType = TypeVar('_V1ValidatorType', V1Validator, _PartialClsOrStaticMethod)
|
|
65
|
+
_V1RootValidatorFunctionType = TypeVar(
|
|
66
|
+
'_V1RootValidatorFunctionType',
|
|
67
|
+
_decorators_v1.V1RootValidatorFunction,
|
|
68
|
+
_V1RootValidatorClsMethod,
|
|
69
|
+
_PartialClsOrStaticMethod,
|
|
70
|
+
)
|
|
71
|
+
else:
|
|
72
|
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
|
73
|
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
|
74
|
+
DeprecationWarning = PydanticDeprecatedSince20
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@deprecated(
|
|
78
|
+
'Pydantic V1 style `@validator` validators are deprecated.'
|
|
79
|
+
' You should migrate to Pydantic V2 style `@field_validator` validators,'
|
|
80
|
+
' see the migration guide for more details',
|
|
81
|
+
category=None,
|
|
82
|
+
)
|
|
83
|
+
def validator(
|
|
84
|
+
__field: str,
|
|
85
|
+
*fields: str,
|
|
86
|
+
pre: bool = False,
|
|
87
|
+
each_item: bool = False,
|
|
88
|
+
always: bool = False,
|
|
89
|
+
check_fields: bool | None = None,
|
|
90
|
+
allow_reuse: bool = False,
|
|
91
|
+
) -> Callable[[_V1ValidatorType], _V1ValidatorType]:
|
|
92
|
+
"""Decorate methods on the class indicating that they should be used to validate fields.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
__field (str): The first field the validator should be called on; this is separate
|
|
96
|
+
from `fields` to ensure an error is raised if you don't pass at least one.
|
|
97
|
+
*fields (str): Additional field(s) the validator should be called on.
|
|
98
|
+
pre (bool, optional): Whether this validator should be called before the standard
|
|
99
|
+
validators (else after). Defaults to False.
|
|
100
|
+
each_item (bool, optional): For complex objects (sets, lists etc.) whether to validate
|
|
101
|
+
individual elements rather than the whole object. Defaults to False.
|
|
102
|
+
always (bool, optional): Whether this method and other validators should be called even if
|
|
103
|
+
the value is missing. Defaults to False.
|
|
104
|
+
check_fields (bool | None, optional): Whether to check that the fields actually exist on the model.
|
|
105
|
+
Defaults to None.
|
|
106
|
+
allow_reuse (bool, optional): Whether to track and raise an error if another validator refers to
|
|
107
|
+
the decorated function. Defaults to False.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
Callable: A decorator that can be used to decorate a
|
|
111
|
+
function to be used as a validator.
|
|
112
|
+
"""
|
|
113
|
+
warn(
|
|
114
|
+
'Pydantic V1 style `@validator` validators are deprecated.'
|
|
115
|
+
' You should migrate to Pydantic V2 style `@field_validator` validators,'
|
|
116
|
+
' see the migration guide for more details',
|
|
117
|
+
DeprecationWarning,
|
|
118
|
+
stacklevel=2,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
if allow_reuse is True: # pragma: no cover
|
|
122
|
+
warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning, stacklevel=2)
|
|
123
|
+
fields = __field, *fields
|
|
124
|
+
if isinstance(fields[0], FunctionType):
|
|
125
|
+
raise PydanticUserError(
|
|
126
|
+
'`@validator` should be used with fields and keyword arguments, not bare. '
|
|
127
|
+
"E.g. usage should be `@validator('<field_name>', ...)`",
|
|
128
|
+
code='decorator-missing-arguments',
|
|
129
|
+
)
|
|
130
|
+
elif not all(isinstance(field, str) for field in fields):
|
|
131
|
+
raise PydanticUserError(
|
|
132
|
+
'`@validator` fields should be passed as separate string args. '
|
|
133
|
+
"E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`",
|
|
134
|
+
code='decorator-invalid-fields',
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
mode: Literal['before', 'after'] = 'before' if pre is True else 'after'
|
|
138
|
+
|
|
139
|
+
def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]:
|
|
140
|
+
if _decorators.is_instance_method_from_sig(f):
|
|
141
|
+
raise PydanticUserError(
|
|
142
|
+
'`@validator` cannot be applied to instance methods', code='validator-instance-method'
|
|
143
|
+
)
|
|
144
|
+
# auto apply the @classmethod decorator
|
|
145
|
+
f = _decorators.ensure_classmethod_based_on_signature(f)
|
|
146
|
+
wrap = _decorators_v1.make_generic_v1_field_validator
|
|
147
|
+
validator_wrapper_info = _decorators.ValidatorDecoratorInfo(
|
|
148
|
+
fields=fields,
|
|
149
|
+
mode=mode,
|
|
150
|
+
each_item=each_item,
|
|
151
|
+
always=always,
|
|
152
|
+
check_fields=check_fields,
|
|
153
|
+
)
|
|
154
|
+
return _decorators.PydanticDescriptorProxy(f, validator_wrapper_info, shim=wrap)
|
|
155
|
+
|
|
156
|
+
return dec # type: ignore[return-value]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@overload
|
|
160
|
+
def root_validator(
|
|
161
|
+
*,
|
|
162
|
+
# if you don't specify `pre` the default is `pre=False`
|
|
163
|
+
# which means you need to specify `skip_on_failure=True`
|
|
164
|
+
skip_on_failure: Literal[True],
|
|
165
|
+
allow_reuse: bool = ...,
|
|
166
|
+
) -> Callable[
|
|
167
|
+
[_V1RootValidatorFunctionType],
|
|
168
|
+
_V1RootValidatorFunctionType,
|
|
169
|
+
]: ...
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@overload
|
|
173
|
+
def root_validator(
|
|
174
|
+
*,
|
|
175
|
+
# if you specify `pre=True` then you don't need to specify
|
|
176
|
+
# `skip_on_failure`, in fact it is not allowed as an argument!
|
|
177
|
+
pre: Literal[True],
|
|
178
|
+
allow_reuse: bool = ...,
|
|
179
|
+
) -> Callable[
|
|
180
|
+
[_V1RootValidatorFunctionType],
|
|
181
|
+
_V1RootValidatorFunctionType,
|
|
182
|
+
]: ...
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@overload
|
|
186
|
+
def root_validator(
|
|
187
|
+
*,
|
|
188
|
+
# if you explicitly specify `pre=False` then you
|
|
189
|
+
# MUST specify `skip_on_failure=True`
|
|
190
|
+
pre: Literal[False],
|
|
191
|
+
skip_on_failure: Literal[True],
|
|
192
|
+
allow_reuse: bool = ...,
|
|
193
|
+
) -> Callable[
|
|
194
|
+
[_V1RootValidatorFunctionType],
|
|
195
|
+
_V1RootValidatorFunctionType,
|
|
196
|
+
]: ...
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@deprecated(
|
|
200
|
+
'Pydantic V1 style `@root_validator` validators are deprecated.'
|
|
201
|
+
' You should migrate to Pydantic V2 style `@model_validator` validators,'
|
|
202
|
+
' see the migration guide for more details',
|
|
203
|
+
category=None,
|
|
204
|
+
)
|
|
205
|
+
def root_validator(
|
|
206
|
+
*__args,
|
|
207
|
+
pre: bool = False,
|
|
208
|
+
skip_on_failure: bool = False,
|
|
209
|
+
allow_reuse: bool = False,
|
|
210
|
+
) -> Any:
|
|
211
|
+
"""Decorate methods on a model indicating that they should be used to validate (and perhaps
|
|
212
|
+
modify) data either before or after standard model parsing/validation is performed.
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
pre (bool, optional): Whether this validator should be called before the standard
|
|
216
|
+
validators (else after). Defaults to False.
|
|
217
|
+
skip_on_failure (bool, optional): Whether to stop validation and return as soon as a
|
|
218
|
+
failure is encountered. Defaults to False.
|
|
219
|
+
allow_reuse (bool, optional): Whether to track and raise an error if another validator
|
|
220
|
+
refers to the decorated function. Defaults to False.
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
Any: A decorator that can be used to decorate a function to be used as a root_validator.
|
|
224
|
+
"""
|
|
225
|
+
warn(
|
|
226
|
+
'Pydantic V1 style `@root_validator` validators are deprecated.'
|
|
227
|
+
' You should migrate to Pydantic V2 style `@model_validator` validators,'
|
|
228
|
+
' see the migration guide for more details',
|
|
229
|
+
DeprecationWarning,
|
|
230
|
+
stacklevel=2,
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
if __args:
|
|
234
|
+
# Ensure a nice error is raised if someone attempts to use the bare decorator
|
|
235
|
+
return root_validator()(*__args) # type: ignore
|
|
236
|
+
|
|
237
|
+
if allow_reuse is True: # pragma: no cover
|
|
238
|
+
warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning, stacklevel=2)
|
|
239
|
+
mode: Literal['before', 'after'] = 'before' if pre is True else 'after'
|
|
240
|
+
if pre is False and skip_on_failure is not True:
|
|
241
|
+
raise PydanticUserError(
|
|
242
|
+
'If you use `@root_validator` with pre=False (the default) you MUST specify `skip_on_failure=True`.'
|
|
243
|
+
' Note that `@root_validator` is deprecated and should be replaced with `@model_validator`.',
|
|
244
|
+
code='root-validator-pre-skip',
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
wrap = partial(_decorators_v1.make_v1_generic_root_validator, pre=pre)
|
|
248
|
+
|
|
249
|
+
def dec(f: Callable[..., Any] | classmethod[Any, Any, Any] | staticmethod[Any, Any]) -> Any:
|
|
250
|
+
if _decorators.is_instance_method_from_sig(f):
|
|
251
|
+
raise TypeError('`@root_validator` cannot be applied to instance methods')
|
|
252
|
+
# auto apply the @classmethod decorator
|
|
253
|
+
res = _decorators.ensure_classmethod_based_on_signature(f)
|
|
254
|
+
dec_info = _decorators.RootValidatorDecoratorInfo(mode=mode)
|
|
255
|
+
return _decorators.PydanticDescriptorProxy(res, dec_info, shim=wrap)
|
|
256
|
+
|
|
257
|
+
return dec
|