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,72 @@
|
|
|
1
|
+
from __future__ import annotations as _annotations
|
|
2
|
+
|
|
3
|
+
import warnings
|
|
4
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
5
|
+
|
|
6
|
+
from typing_extensions import deprecated
|
|
7
|
+
|
|
8
|
+
from .._internal import _config
|
|
9
|
+
from ..warnings import PydanticDeprecatedSince20
|
|
10
|
+
|
|
11
|
+
if not TYPE_CHECKING:
|
|
12
|
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
|
13
|
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
|
14
|
+
DeprecationWarning = PydanticDeprecatedSince20
|
|
15
|
+
|
|
16
|
+
__all__ = 'BaseConfig', 'Extra'
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _ConfigMetaclass(type):
|
|
20
|
+
def __getattr__(self, item: str) -> Any:
|
|
21
|
+
try:
|
|
22
|
+
obj = _config.config_defaults[item]
|
|
23
|
+
warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
|
|
24
|
+
return obj
|
|
25
|
+
except KeyError as exc:
|
|
26
|
+
raise AttributeError(f"type object '{self.__name__}' has no attribute {exc}") from exc
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@deprecated('BaseConfig is deprecated. Use the `pboot_validator.ConfigDict` instead.', category=PydanticDeprecatedSince20)
|
|
30
|
+
class BaseConfig(metaclass=_ConfigMetaclass):
|
|
31
|
+
"""This class is only retained for backwards compatibility.
|
|
32
|
+
|
|
33
|
+
!!! Warning "Deprecated"
|
|
34
|
+
BaseConfig is deprecated. Use the [`pboot_validator.ConfigDict`][pboot_validator.ConfigDict] instead.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __getattr__(self, item: str) -> Any:
|
|
38
|
+
try:
|
|
39
|
+
obj = super().__getattribute__(item)
|
|
40
|
+
warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
|
|
41
|
+
return obj
|
|
42
|
+
except AttributeError as exc:
|
|
43
|
+
try:
|
|
44
|
+
return getattr(type(self), item)
|
|
45
|
+
except AttributeError:
|
|
46
|
+
# re-raising changes the displayed text to reflect that `self` is not a type
|
|
47
|
+
raise AttributeError(str(exc)) from exc
|
|
48
|
+
|
|
49
|
+
def __init_subclass__(cls, **kwargs: Any) -> None:
|
|
50
|
+
warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
|
|
51
|
+
return super().__init_subclass__(**kwargs)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _ExtraMeta(type):
|
|
55
|
+
def __getattribute__(self, __name: str) -> Any:
|
|
56
|
+
# The @deprecated decorator accesses other attributes, so we only emit a warning for the expected ones
|
|
57
|
+
if __name in {'allow', 'ignore', 'forbid'}:
|
|
58
|
+
warnings.warn(
|
|
59
|
+
"`pboot_validator.config.Extra` is deprecated, use literal values instead (e.g. `extra='allow'`)",
|
|
60
|
+
DeprecationWarning,
|
|
61
|
+
stacklevel=2,
|
|
62
|
+
)
|
|
63
|
+
return super().__getattribute__(__name)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@deprecated(
|
|
67
|
+
"Extra is deprecated. Use literal values instead (e.g. `extra='allow'`)", category=PydanticDeprecatedSince20
|
|
68
|
+
)
|
|
69
|
+
class Extra(metaclass=_ExtraMeta):
|
|
70
|
+
allow: Literal['allow'] = 'allow'
|
|
71
|
+
ignore: Literal['ignore'] = 'ignore'
|
|
72
|
+
forbid: Literal['forbid'] = 'forbid'
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
from __future__ import annotations as _annotations
|
|
2
|
+
|
|
3
|
+
import typing
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import typing_extensions
|
|
9
|
+
|
|
10
|
+
from .._internal import (
|
|
11
|
+
_model_construction,
|
|
12
|
+
_typing_extra,
|
|
13
|
+
_utils,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
if typing.TYPE_CHECKING:
|
|
17
|
+
from .. import BaseModel
|
|
18
|
+
from .._internal._utils import AbstractSetIntStr, MappingIntStrAny
|
|
19
|
+
|
|
20
|
+
AnyClassMethod = classmethod[Any, Any, Any]
|
|
21
|
+
TupleGenerator = typing.Generator[tuple[str, Any], None, None]
|
|
22
|
+
Model = typing.TypeVar('Model', bound='BaseModel')
|
|
23
|
+
# should be `set[int] | set[str] | dict[int, IncEx] | dict[str, IncEx] | None`, but mypy can't cope
|
|
24
|
+
IncEx: typing_extensions.TypeAlias = 'set[int] | set[str] | dict[int, Any] | dict[str, Any] | None'
|
|
25
|
+
|
|
26
|
+
_object_setattr = _model_construction.object_setattr
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _iter(
|
|
30
|
+
self: BaseModel,
|
|
31
|
+
to_dict: bool = False,
|
|
32
|
+
by_alias: bool = False,
|
|
33
|
+
include: AbstractSetIntStr | MappingIntStrAny | None = None,
|
|
34
|
+
exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
|
|
35
|
+
exclude_unset: bool = False,
|
|
36
|
+
exclude_defaults: bool = False,
|
|
37
|
+
exclude_none: bool = False,
|
|
38
|
+
) -> TupleGenerator:
|
|
39
|
+
# Merge field set excludes with explicit exclude parameter with explicit overriding field set options.
|
|
40
|
+
# The extra "is not None" guards are not logically necessary but optimizes performance for the simple case.
|
|
41
|
+
if exclude is not None:
|
|
42
|
+
exclude = _utils.ValueItems.merge(
|
|
43
|
+
{k: v.exclude for k, v in self.__pydantic_fields__.items() if v.exclude is not None}, exclude
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
if include is not None:
|
|
47
|
+
include = _utils.ValueItems.merge(dict.fromkeys(self.__pydantic_fields__, True), include, intersect=True)
|
|
48
|
+
|
|
49
|
+
allowed_keys = _calculate_keys(self, include=include, exclude=exclude, exclude_unset=exclude_unset) # type: ignore
|
|
50
|
+
if allowed_keys is None and not (to_dict or by_alias or exclude_unset or exclude_defaults or exclude_none):
|
|
51
|
+
# huge boost for plain _iter()
|
|
52
|
+
yield from self.__dict__.items()
|
|
53
|
+
if self.__pydantic_extra__:
|
|
54
|
+
yield from self.__pydantic_extra__.items()
|
|
55
|
+
return
|
|
56
|
+
|
|
57
|
+
value_exclude = _utils.ValueItems(self, exclude) if exclude is not None else None
|
|
58
|
+
value_include = _utils.ValueItems(self, include) if include is not None else None
|
|
59
|
+
|
|
60
|
+
if self.__pydantic_extra__ is None:
|
|
61
|
+
items = self.__dict__.items()
|
|
62
|
+
else:
|
|
63
|
+
items = list(self.__dict__.items()) + list(self.__pydantic_extra__.items())
|
|
64
|
+
|
|
65
|
+
for field_key, v in items:
|
|
66
|
+
if (allowed_keys is not None and field_key not in allowed_keys) or (exclude_none and v is None):
|
|
67
|
+
continue
|
|
68
|
+
|
|
69
|
+
if exclude_defaults:
|
|
70
|
+
try:
|
|
71
|
+
field = self.__pydantic_fields__[field_key]
|
|
72
|
+
except KeyError:
|
|
73
|
+
pass
|
|
74
|
+
else:
|
|
75
|
+
if not field.is_required() and field.default == v:
|
|
76
|
+
continue
|
|
77
|
+
|
|
78
|
+
if by_alias and field_key in self.__pydantic_fields__:
|
|
79
|
+
dict_key = self.__pydantic_fields__[field_key].alias or field_key
|
|
80
|
+
else:
|
|
81
|
+
dict_key = field_key
|
|
82
|
+
|
|
83
|
+
if to_dict or value_include or value_exclude:
|
|
84
|
+
v = _get_value(
|
|
85
|
+
type(self),
|
|
86
|
+
v,
|
|
87
|
+
to_dict=to_dict,
|
|
88
|
+
by_alias=by_alias,
|
|
89
|
+
include=value_include and value_include.for_element(field_key),
|
|
90
|
+
exclude=value_exclude and value_exclude.for_element(field_key),
|
|
91
|
+
exclude_unset=exclude_unset,
|
|
92
|
+
exclude_defaults=exclude_defaults,
|
|
93
|
+
exclude_none=exclude_none,
|
|
94
|
+
)
|
|
95
|
+
yield dict_key, v
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _copy_and_set_values(
|
|
99
|
+
self: Model,
|
|
100
|
+
values: dict[str, Any],
|
|
101
|
+
fields_set: set[str],
|
|
102
|
+
extra: dict[str, Any] | None = None,
|
|
103
|
+
private: dict[str, Any] | None = None,
|
|
104
|
+
*,
|
|
105
|
+
deep: bool, # UP006
|
|
106
|
+
) -> Model:
|
|
107
|
+
if deep:
|
|
108
|
+
# chances of having empty dict here are quite low for using smart_deepcopy
|
|
109
|
+
values = deepcopy(values)
|
|
110
|
+
extra = deepcopy(extra)
|
|
111
|
+
private = deepcopy(private)
|
|
112
|
+
|
|
113
|
+
cls = self.__class__
|
|
114
|
+
m = cls.__new__(cls)
|
|
115
|
+
_object_setattr(m, '__dict__', values)
|
|
116
|
+
_object_setattr(m, '__pydantic_extra__', extra)
|
|
117
|
+
_object_setattr(m, '__pydantic_fields_set__', fields_set)
|
|
118
|
+
_object_setattr(m, '__pydantic_private__', private)
|
|
119
|
+
|
|
120
|
+
return m
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@typing.no_type_check
|
|
124
|
+
def _get_value(
|
|
125
|
+
cls: type[BaseModel],
|
|
126
|
+
v: Any,
|
|
127
|
+
to_dict: bool,
|
|
128
|
+
by_alias: bool,
|
|
129
|
+
include: AbstractSetIntStr | MappingIntStrAny | None,
|
|
130
|
+
exclude: AbstractSetIntStr | MappingIntStrAny | None,
|
|
131
|
+
exclude_unset: bool,
|
|
132
|
+
exclude_defaults: bool,
|
|
133
|
+
exclude_none: bool,
|
|
134
|
+
) -> Any:
|
|
135
|
+
from .. import BaseModel
|
|
136
|
+
|
|
137
|
+
if isinstance(v, BaseModel):
|
|
138
|
+
if to_dict:
|
|
139
|
+
return v.model_dump(
|
|
140
|
+
by_alias=by_alias,
|
|
141
|
+
exclude_unset=exclude_unset,
|
|
142
|
+
exclude_defaults=exclude_defaults,
|
|
143
|
+
include=include, # type: ignore
|
|
144
|
+
exclude=exclude, # type: ignore
|
|
145
|
+
exclude_none=exclude_none,
|
|
146
|
+
)
|
|
147
|
+
else:
|
|
148
|
+
return v.copy(include=include, exclude=exclude)
|
|
149
|
+
|
|
150
|
+
value_exclude = _utils.ValueItems(v, exclude) if exclude else None
|
|
151
|
+
value_include = _utils.ValueItems(v, include) if include else None
|
|
152
|
+
|
|
153
|
+
if isinstance(v, dict):
|
|
154
|
+
return {
|
|
155
|
+
k_: _get_value(
|
|
156
|
+
cls,
|
|
157
|
+
v_,
|
|
158
|
+
to_dict=to_dict,
|
|
159
|
+
by_alias=by_alias,
|
|
160
|
+
exclude_unset=exclude_unset,
|
|
161
|
+
exclude_defaults=exclude_defaults,
|
|
162
|
+
include=value_include and value_include.for_element(k_),
|
|
163
|
+
exclude=value_exclude and value_exclude.for_element(k_),
|
|
164
|
+
exclude_none=exclude_none,
|
|
165
|
+
)
|
|
166
|
+
for k_, v_ in v.items()
|
|
167
|
+
if (not value_exclude or not value_exclude.is_excluded(k_))
|
|
168
|
+
and (not value_include or value_include.is_included(k_))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
elif _utils.sequence_like(v):
|
|
172
|
+
seq_args = (
|
|
173
|
+
_get_value(
|
|
174
|
+
cls,
|
|
175
|
+
v_,
|
|
176
|
+
to_dict=to_dict,
|
|
177
|
+
by_alias=by_alias,
|
|
178
|
+
exclude_unset=exclude_unset,
|
|
179
|
+
exclude_defaults=exclude_defaults,
|
|
180
|
+
include=value_include and value_include.for_element(i),
|
|
181
|
+
exclude=value_exclude and value_exclude.for_element(i),
|
|
182
|
+
exclude_none=exclude_none,
|
|
183
|
+
)
|
|
184
|
+
for i, v_ in enumerate(v)
|
|
185
|
+
if (not value_exclude or not value_exclude.is_excluded(i))
|
|
186
|
+
and (not value_include or value_include.is_included(i))
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
return v.__class__(*seq_args) if _typing_extra.is_namedtuple(v.__class__) else v.__class__(seq_args)
|
|
190
|
+
|
|
191
|
+
elif isinstance(v, Enum) and getattr(cls.model_config, 'use_enum_values', False):
|
|
192
|
+
return v.value
|
|
193
|
+
|
|
194
|
+
else:
|
|
195
|
+
return v
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _calculate_keys(
|
|
199
|
+
self: BaseModel,
|
|
200
|
+
include: MappingIntStrAny | None,
|
|
201
|
+
exclude: MappingIntStrAny | None,
|
|
202
|
+
exclude_unset: bool,
|
|
203
|
+
update: dict[str, Any] | None = None, # noqa UP006
|
|
204
|
+
) -> typing.AbstractSet[str] | None:
|
|
205
|
+
if include is None and exclude is None and exclude_unset is False:
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
keys: typing.AbstractSet[str]
|
|
209
|
+
if exclude_unset:
|
|
210
|
+
keys = self.__pydantic_fields_set__.copy()
|
|
211
|
+
else:
|
|
212
|
+
keys = set(self.__dict__.keys())
|
|
213
|
+
keys = keys | (self.__pydantic_extra__ or {}).keys()
|
|
214
|
+
|
|
215
|
+
if include is not None:
|
|
216
|
+
keys &= include.keys()
|
|
217
|
+
|
|
218
|
+
if update:
|
|
219
|
+
keys -= update.keys()
|
|
220
|
+
|
|
221
|
+
if exclude:
|
|
222
|
+
keys -= {k for k, v in exclude.items() if _utils.ValueItems.is_true(v)}
|
|
223
|
+
|
|
224
|
+
return keys
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
from collections.abc import Callable, Mapping
|
|
3
|
+
from functools import wraps
|
|
4
|
+
from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union, get_type_hints, overload
|
|
5
|
+
|
|
6
|
+
from typing_extensions import deprecated
|
|
7
|
+
|
|
8
|
+
from .._internal import _config
|
|
9
|
+
from ..alias_generators import to_pascal
|
|
10
|
+
from ..errors import PydanticUserError
|
|
11
|
+
from ..functional_validators import field_validator
|
|
12
|
+
from ..main import BaseModel, create_model
|
|
13
|
+
from ..warnings import PydanticDeprecatedSince20
|
|
14
|
+
|
|
15
|
+
if not TYPE_CHECKING:
|
|
16
|
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
|
17
|
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
|
18
|
+
DeprecationWarning = PydanticDeprecatedSince20
|
|
19
|
+
|
|
20
|
+
__all__ = ('validate_arguments',)
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
AnyCallable = Callable[..., Any]
|
|
24
|
+
|
|
25
|
+
AnyCallableT = TypeVar('AnyCallableT', bound=AnyCallable)
|
|
26
|
+
ConfigType = Union[None, type[Any], dict[str, Any]]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@overload
|
|
30
|
+
def validate_arguments(
|
|
31
|
+
func: None = None, *, config: 'ConfigType' = None
|
|
32
|
+
) -> Callable[['AnyCallableT'], 'AnyCallableT']: ...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@overload
|
|
36
|
+
def validate_arguments(func: 'AnyCallableT') -> 'AnyCallableT': ...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@deprecated(
|
|
40
|
+
'The `validate_arguments` method is deprecated; use `validate_call` instead.',
|
|
41
|
+
category=None,
|
|
42
|
+
)
|
|
43
|
+
def validate_arguments(func: Optional['AnyCallableT'] = None, *, config: 'ConfigType' = None) -> Any:
|
|
44
|
+
"""Decorator to validate the arguments passed to a function."""
|
|
45
|
+
warnings.warn(
|
|
46
|
+
'The `validate_arguments` method is deprecated; use `validate_call` instead.',
|
|
47
|
+
PydanticDeprecatedSince20,
|
|
48
|
+
stacklevel=2,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
def validate(_func: 'AnyCallable') -> 'AnyCallable':
|
|
52
|
+
vd = ValidatedFunction(_func, config)
|
|
53
|
+
|
|
54
|
+
@wraps(_func)
|
|
55
|
+
def wrapper_function(*args: Any, **kwargs: Any) -> Any:
|
|
56
|
+
return vd.call(*args, **kwargs)
|
|
57
|
+
|
|
58
|
+
wrapper_function.vd = vd # type: ignore
|
|
59
|
+
wrapper_function.validate = vd.init_model_instance # type: ignore
|
|
60
|
+
wrapper_function.raw_function = vd.raw_function # type: ignore
|
|
61
|
+
wrapper_function.model = vd.model # type: ignore
|
|
62
|
+
return wrapper_function
|
|
63
|
+
|
|
64
|
+
if func:
|
|
65
|
+
return validate(func)
|
|
66
|
+
else:
|
|
67
|
+
return validate
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
ALT_V_ARGS = 'v__args'
|
|
71
|
+
ALT_V_KWARGS = 'v__kwargs'
|
|
72
|
+
V_POSITIONAL_ONLY_NAME = 'v__positional_only'
|
|
73
|
+
V_DUPLICATE_KWARGS = 'v__duplicate_kwargs'
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ValidatedFunction:
|
|
77
|
+
def __init__(self, function: 'AnyCallable', config: 'ConfigType'):
|
|
78
|
+
from inspect import Parameter, signature
|
|
79
|
+
|
|
80
|
+
parameters: Mapping[str, Parameter] = signature(function).parameters
|
|
81
|
+
|
|
82
|
+
if parameters.keys() & {ALT_V_ARGS, ALT_V_KWARGS, V_POSITIONAL_ONLY_NAME, V_DUPLICATE_KWARGS}:
|
|
83
|
+
raise PydanticUserError(
|
|
84
|
+
f'"{ALT_V_ARGS}", "{ALT_V_KWARGS}", "{V_POSITIONAL_ONLY_NAME}" and "{V_DUPLICATE_KWARGS}" '
|
|
85
|
+
f'are not permitted as argument names when using the "{validate_arguments.__name__}" decorator',
|
|
86
|
+
code=None,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
self.raw_function = function
|
|
90
|
+
self.arg_mapping: dict[int, str] = {}
|
|
91
|
+
self.positional_only_args: set[str] = set()
|
|
92
|
+
self.v_args_name = 'args'
|
|
93
|
+
self.v_kwargs_name = 'kwargs'
|
|
94
|
+
|
|
95
|
+
type_hints = get_type_hints(function, include_extras=True)
|
|
96
|
+
takes_args = False
|
|
97
|
+
takes_kwargs = False
|
|
98
|
+
fields: dict[str, tuple[Any, Any]] = {}
|
|
99
|
+
for i, (name, p) in enumerate(parameters.items()):
|
|
100
|
+
if p.annotation is p.empty:
|
|
101
|
+
annotation = Any
|
|
102
|
+
else:
|
|
103
|
+
annotation = type_hints[name]
|
|
104
|
+
|
|
105
|
+
default = ... if p.default is p.empty else p.default
|
|
106
|
+
if p.kind == Parameter.POSITIONAL_ONLY:
|
|
107
|
+
self.arg_mapping[i] = name
|
|
108
|
+
fields[name] = annotation, default
|
|
109
|
+
fields[V_POSITIONAL_ONLY_NAME] = list[str], None
|
|
110
|
+
self.positional_only_args.add(name)
|
|
111
|
+
elif p.kind == Parameter.POSITIONAL_OR_KEYWORD:
|
|
112
|
+
self.arg_mapping[i] = name
|
|
113
|
+
fields[name] = annotation, default
|
|
114
|
+
fields[V_DUPLICATE_KWARGS] = list[str], None
|
|
115
|
+
elif p.kind == Parameter.KEYWORD_ONLY:
|
|
116
|
+
fields[name] = annotation, default
|
|
117
|
+
elif p.kind == Parameter.VAR_POSITIONAL:
|
|
118
|
+
self.v_args_name = name
|
|
119
|
+
fields[name] = tuple[annotation, ...], None
|
|
120
|
+
takes_args = True
|
|
121
|
+
else:
|
|
122
|
+
assert p.kind == Parameter.VAR_KEYWORD, p.kind
|
|
123
|
+
self.v_kwargs_name = name
|
|
124
|
+
fields[name] = dict[str, annotation], None
|
|
125
|
+
takes_kwargs = True
|
|
126
|
+
|
|
127
|
+
# these checks avoid a clash between "args" and a field with that name
|
|
128
|
+
if not takes_args and self.v_args_name in fields:
|
|
129
|
+
self.v_args_name = ALT_V_ARGS
|
|
130
|
+
|
|
131
|
+
# same with "kwargs"
|
|
132
|
+
if not takes_kwargs and self.v_kwargs_name in fields:
|
|
133
|
+
self.v_kwargs_name = ALT_V_KWARGS
|
|
134
|
+
|
|
135
|
+
if not takes_args:
|
|
136
|
+
# we add the field so validation below can raise the correct exception
|
|
137
|
+
fields[self.v_args_name] = list[Any], None
|
|
138
|
+
|
|
139
|
+
if not takes_kwargs:
|
|
140
|
+
# same with kwargs
|
|
141
|
+
fields[self.v_kwargs_name] = dict[Any, Any], None
|
|
142
|
+
|
|
143
|
+
self.create_model(fields, takes_args, takes_kwargs, config)
|
|
144
|
+
|
|
145
|
+
def init_model_instance(self, *args: Any, **kwargs: Any) -> BaseModel:
|
|
146
|
+
values = self.build_values(args, kwargs)
|
|
147
|
+
return self.model(**values)
|
|
148
|
+
|
|
149
|
+
def call(self, *args: Any, **kwargs: Any) -> Any:
|
|
150
|
+
m = self.init_model_instance(*args, **kwargs)
|
|
151
|
+
return self.execute(m)
|
|
152
|
+
|
|
153
|
+
def build_values(self, args: tuple[Any, ...], kwargs: dict[str, Any]) -> dict[str, Any]:
|
|
154
|
+
values: dict[str, Any] = {}
|
|
155
|
+
if args:
|
|
156
|
+
arg_iter = enumerate(args)
|
|
157
|
+
while True:
|
|
158
|
+
try:
|
|
159
|
+
i, a = next(arg_iter)
|
|
160
|
+
except StopIteration:
|
|
161
|
+
break
|
|
162
|
+
arg_name = self.arg_mapping.get(i)
|
|
163
|
+
if arg_name is not None:
|
|
164
|
+
values[arg_name] = a
|
|
165
|
+
else:
|
|
166
|
+
values[self.v_args_name] = [a] + [a for _, a in arg_iter]
|
|
167
|
+
break
|
|
168
|
+
|
|
169
|
+
var_kwargs: dict[str, Any] = {}
|
|
170
|
+
wrong_positional_args = []
|
|
171
|
+
duplicate_kwargs = []
|
|
172
|
+
fields_alias = [
|
|
173
|
+
field.alias
|
|
174
|
+
for name, field in self.model.__pydantic_fields__.items()
|
|
175
|
+
if name not in (self.v_args_name, self.v_kwargs_name)
|
|
176
|
+
]
|
|
177
|
+
non_var_fields = set(self.model.__pydantic_fields__) - {self.v_args_name, self.v_kwargs_name}
|
|
178
|
+
for k, v in kwargs.items():
|
|
179
|
+
if k in non_var_fields or k in fields_alias:
|
|
180
|
+
if k in self.positional_only_args:
|
|
181
|
+
wrong_positional_args.append(k)
|
|
182
|
+
if k in values:
|
|
183
|
+
duplicate_kwargs.append(k)
|
|
184
|
+
values[k] = v
|
|
185
|
+
else:
|
|
186
|
+
var_kwargs[k] = v
|
|
187
|
+
|
|
188
|
+
if var_kwargs:
|
|
189
|
+
values[self.v_kwargs_name] = var_kwargs
|
|
190
|
+
if wrong_positional_args:
|
|
191
|
+
values[V_POSITIONAL_ONLY_NAME] = wrong_positional_args
|
|
192
|
+
if duplicate_kwargs:
|
|
193
|
+
values[V_DUPLICATE_KWARGS] = duplicate_kwargs
|
|
194
|
+
return values
|
|
195
|
+
|
|
196
|
+
def execute(self, m: BaseModel) -> Any:
|
|
197
|
+
d = {
|
|
198
|
+
k: v
|
|
199
|
+
for k, v in m.__dict__.items()
|
|
200
|
+
if k in m.__pydantic_fields_set__ or m.__pydantic_fields__[k].default_factory
|
|
201
|
+
}
|
|
202
|
+
var_kwargs = d.pop(self.v_kwargs_name, {})
|
|
203
|
+
|
|
204
|
+
if self.v_args_name in d:
|
|
205
|
+
args_: list[Any] = []
|
|
206
|
+
in_kwargs = False
|
|
207
|
+
kwargs = {}
|
|
208
|
+
for name, value in d.items():
|
|
209
|
+
if in_kwargs:
|
|
210
|
+
kwargs[name] = value
|
|
211
|
+
elif name == self.v_args_name:
|
|
212
|
+
args_ += value
|
|
213
|
+
in_kwargs = True
|
|
214
|
+
else:
|
|
215
|
+
args_.append(value)
|
|
216
|
+
return self.raw_function(*args_, **kwargs, **var_kwargs)
|
|
217
|
+
elif self.positional_only_args:
|
|
218
|
+
args_ = []
|
|
219
|
+
kwargs = {}
|
|
220
|
+
for name, value in d.items():
|
|
221
|
+
if name in self.positional_only_args:
|
|
222
|
+
args_.append(value)
|
|
223
|
+
else:
|
|
224
|
+
kwargs[name] = value
|
|
225
|
+
return self.raw_function(*args_, **kwargs, **var_kwargs)
|
|
226
|
+
else:
|
|
227
|
+
return self.raw_function(**d, **var_kwargs)
|
|
228
|
+
|
|
229
|
+
def create_model(self, fields: dict[str, Any], takes_args: bool, takes_kwargs: bool, config: 'ConfigType') -> None:
|
|
230
|
+
pos_args = len(self.arg_mapping)
|
|
231
|
+
|
|
232
|
+
config_dict = _config.prepare_config(config)
|
|
233
|
+
|
|
234
|
+
if config_dict.get('alias_generator'):
|
|
235
|
+
raise PydanticUserError(
|
|
236
|
+
'Setting the "alias_generator" property on custom Config for '
|
|
237
|
+
'@validate_arguments is not yet supported, please remove.',
|
|
238
|
+
code=None,
|
|
239
|
+
)
|
|
240
|
+
if config_dict.get('extra') is None:
|
|
241
|
+
config_dict['extra'] = 'forbid'
|
|
242
|
+
|
|
243
|
+
config_wrapper = _config.ConfigWrapper(config_dict, check=False)
|
|
244
|
+
|
|
245
|
+
class DecoratorBaseModel(BaseModel):
|
|
246
|
+
@field_validator(self.v_args_name, check_fields=False)
|
|
247
|
+
@classmethod
|
|
248
|
+
def check_args(cls, v: list[Any] | None) -> list[Any] | None:
|
|
249
|
+
if takes_args or v is None:
|
|
250
|
+
return v
|
|
251
|
+
|
|
252
|
+
raise TypeError(f'{pos_args} positional arguments expected but {pos_args + len(v)} given')
|
|
253
|
+
|
|
254
|
+
@field_validator(self.v_kwargs_name, check_fields=False)
|
|
255
|
+
@classmethod
|
|
256
|
+
def check_kwargs(cls, v: dict[str, Any] | None) -> dict[str, Any] | None:
|
|
257
|
+
if takes_kwargs or v is None:
|
|
258
|
+
return v
|
|
259
|
+
|
|
260
|
+
plural = '' if len(v) == 1 else 's'
|
|
261
|
+
keys = ', '.join(map(repr, v.keys()))
|
|
262
|
+
raise TypeError(f'unexpected keyword argument{plural}: {keys}')
|
|
263
|
+
|
|
264
|
+
@field_validator(V_POSITIONAL_ONLY_NAME, check_fields=False)
|
|
265
|
+
@classmethod
|
|
266
|
+
def check_positional_only(cls, v: list[str] | None) -> None:
|
|
267
|
+
if v is None:
|
|
268
|
+
return
|
|
269
|
+
|
|
270
|
+
plural = '' if len(v) == 1 else 's'
|
|
271
|
+
keys = ', '.join(map(repr, v))
|
|
272
|
+
raise TypeError(f'positional-only argument{plural} passed as keyword argument{plural}: {keys}')
|
|
273
|
+
|
|
274
|
+
@field_validator(V_DUPLICATE_KWARGS, check_fields=False)
|
|
275
|
+
@classmethod
|
|
276
|
+
def check_duplicate_kwargs(cls, v: list[str] | None) -> None:
|
|
277
|
+
if v is None:
|
|
278
|
+
return
|
|
279
|
+
|
|
280
|
+
plural = '' if len(v) == 1 else 's'
|
|
281
|
+
keys = ', '.join(map(repr, v))
|
|
282
|
+
raise TypeError(f'multiple values for argument{plural}: {keys}')
|
|
283
|
+
|
|
284
|
+
model_config = config_wrapper.config_dict
|
|
285
|
+
|
|
286
|
+
self.model = create_model(to_pascal(self.raw_function.__name__), __base__=DecoratorBaseModel, **fields)
|