Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step40/zero/3.attention.dense.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step40/zero/3.attention.dense.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step40/zero/3.attention.dense.weight/fp32.pt +3 -0
- ckpts/universal/global_step40/zero/4.attention.query_key_value.weight/fp32.pt +3 -0
- ckpts/universal/global_step40/zero/5.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
- venv/lib/python3.10/site-packages/pydantic/__pycache__/decorator.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/__pycache__/main.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/__pycache__/type_adapter.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/__init__.py +0 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/class_validators.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/config.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/copy_internals.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/decorator.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/json.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/parse.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/tools.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/class_validators.py +265 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/config.py +72 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/copy_internals.py +224 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/decorator.py +279 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/json.py +140 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/parse.py +80 -0
- venv/lib/python3.10/site-packages/pydantic/deprecated/tools.py +103 -0
- venv/lib/python3.10/site-packages/pydantic/plugin/__init__.py +170 -0
- venv/lib/python3.10/site-packages/pydantic/plugin/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/plugin/__pycache__/_loader.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/plugin/__pycache__/_schema_validator.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/plugin/_loader.py +56 -0
- venv/lib/python3.10/site-packages/pydantic/plugin/_schema_validator.py +138 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__init__.py +131 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/_hypothesis_plugin.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/annotated_types.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/class_validators.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/color.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/config.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/dataclasses.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/datetime_parse.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/decorator.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/env_settings.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/fields.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/generics.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/main.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/mypy.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/parse.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/schema.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/tools.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/types.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/typing.cpython-310.pyc +0 -0
ckpts/universal/global_step40/zero/3.attention.dense.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5b588c70cede7ffe1b732d97f8f32ad71485d46da0408df5fae31adcd578134d
|
3 |
+
size 16778396
|
ckpts/universal/global_step40/zero/3.attention.dense.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7aa7db819afbc6acd2148db7d8d6b72aa976ba04911431b65b16c17051115a72
|
3 |
+
size 16778411
|
ckpts/universal/global_step40/zero/3.attention.dense.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c33aed89b6d0e7eb56b961c7fcf71a6634b286fef47dea6f4bdc1c5436d24da8
|
3 |
+
size 16778317
|
ckpts/universal/global_step40/zero/4.attention.query_key_value.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:dd7e146aae41fdbc5f5a689399d9636eb147eddd29ec2f6bf93f171a587683a7
|
3 |
+
size 50332749
|
ckpts/universal/global_step40/zero/5.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b9533d1c9f687b2e0ab23df7a75dac8468253232ce849b3f69478c4896211eca
|
3 |
+
size 33555627
|
venv/lib/python3.10/site-packages/pydantic/__pycache__/decorator.cpython-310.pyc
ADDED
Binary file (331 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pydantic/__pycache__/main.cpython-310.pyc
ADDED
Binary file (47.5 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/__pycache__/type_adapter.cpython-310.pyc
ADDED
Binary file (17.5 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/deprecated/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (187 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/class_validators.cpython-310.pyc
ADDED
Binary file (9.87 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/config.cpython-310.pyc
ADDED
Binary file (3.12 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/copy_internals.cpython-310.pyc
ADDED
Binary file (5.17 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/decorator.cpython-310.pyc
ADDED
Binary file (8.73 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/json.cpython-310.pyc
ADDED
Binary file (4.24 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/parse.cpython-310.pyc
ADDED
Binary file (2.25 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/deprecated/__pycache__/tools.cpython-310.pyc
ADDED
Binary file (2.71 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/deprecated/class_validators.py
ADDED
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Old `@validator` and `@root_validator` function validators from V1."""
|
2 |
+
|
3 |
+
from __future__ import annotations as _annotations
|
4 |
+
|
5 |
+
from functools import partial, partialmethod
|
6 |
+
from types import FunctionType
|
7 |
+
from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union, overload
|
8 |
+
from warnings import warn
|
9 |
+
|
10 |
+
from typing_extensions import Literal, Protocol, TypeAlias, deprecated
|
11 |
+
|
12 |
+
from .._internal import _decorators, _decorators_v1
|
13 |
+
from ..errors import PydanticUserError
|
14 |
+
from ..warnings import PydanticDeprecatedSince20
|
15 |
+
|
16 |
+
_ALLOW_REUSE_WARNING_MESSAGE = '`allow_reuse` is deprecated and will be ignored; it should no longer be necessary'
|
17 |
+
|
18 |
+
|
19 |
+
if TYPE_CHECKING:
|
20 |
+
|
21 |
+
class _OnlyValueValidatorClsMethod(Protocol):
|
22 |
+
def __call__(self, __cls: Any, __value: Any) -> Any:
|
23 |
+
...
|
24 |
+
|
25 |
+
class _V1ValidatorWithValuesClsMethod(Protocol):
|
26 |
+
def __call__(self, __cls: Any, __value: Any, values: dict[str, Any]) -> Any:
|
27 |
+
...
|
28 |
+
|
29 |
+
class _V1ValidatorWithValuesKwOnlyClsMethod(Protocol):
|
30 |
+
def __call__(self, __cls: Any, __value: Any, *, values: dict[str, Any]) -> Any:
|
31 |
+
...
|
32 |
+
|
33 |
+
class _V1ValidatorWithKwargsClsMethod(Protocol):
|
34 |
+
def __call__(self, __cls: Any, **kwargs: Any) -> Any:
|
35 |
+
...
|
36 |
+
|
37 |
+
class _V1ValidatorWithValuesAndKwargsClsMethod(Protocol):
|
38 |
+
def __call__(self, __cls: Any, values: dict[str, Any], **kwargs: Any) -> Any:
|
39 |
+
...
|
40 |
+
|
41 |
+
class _V1RootValidatorClsMethod(Protocol):
|
42 |
+
def __call__(
|
43 |
+
self, __cls: Any, __values: _decorators_v1.RootValidatorValues
|
44 |
+
) -> _decorators_v1.RootValidatorValues:
|
45 |
+
...
|
46 |
+
|
47 |
+
V1Validator = Union[
|
48 |
+
_OnlyValueValidatorClsMethod,
|
49 |
+
_V1ValidatorWithValuesClsMethod,
|
50 |
+
_V1ValidatorWithValuesKwOnlyClsMethod,
|
51 |
+
_V1ValidatorWithKwargsClsMethod,
|
52 |
+
_V1ValidatorWithValuesAndKwargsClsMethod,
|
53 |
+
_decorators_v1.V1ValidatorWithValues,
|
54 |
+
_decorators_v1.V1ValidatorWithValuesKwOnly,
|
55 |
+
_decorators_v1.V1ValidatorWithKwargs,
|
56 |
+
_decorators_v1.V1ValidatorWithValuesAndKwargs,
|
57 |
+
]
|
58 |
+
|
59 |
+
V1RootValidator = Union[
|
60 |
+
_V1RootValidatorClsMethod,
|
61 |
+
_decorators_v1.V1RootValidatorFunction,
|
62 |
+
]
|
63 |
+
|
64 |
+
_PartialClsOrStaticMethod: TypeAlias = Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any]]
|
65 |
+
|
66 |
+
# Allow both a V1 (assumed pre=False) or V2 (assumed mode='after') validator
|
67 |
+
# We lie to type checkers and say we return the same thing we get
|
68 |
+
# but in reality we return a proxy object that _mostly_ behaves like the wrapped thing
|
69 |
+
_V1ValidatorType = TypeVar('_V1ValidatorType', V1Validator, _PartialClsOrStaticMethod)
|
70 |
+
_V1RootValidatorFunctionType = TypeVar(
|
71 |
+
'_V1RootValidatorFunctionType',
|
72 |
+
_decorators_v1.V1RootValidatorFunction,
|
73 |
+
_V1RootValidatorClsMethod,
|
74 |
+
_PartialClsOrStaticMethod,
|
75 |
+
)
|
76 |
+
else:
|
77 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
78 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
79 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
80 |
+
|
81 |
+
|
82 |
+
@deprecated(
|
83 |
+
'Pydantic V1 style `@validator` validators are deprecated.'
|
84 |
+
' You should migrate to Pydantic V2 style `@field_validator` validators,'
|
85 |
+
' see the migration guide for more details',
|
86 |
+
category=None,
|
87 |
+
)
|
88 |
+
def validator(
|
89 |
+
__field: str,
|
90 |
+
*fields: str,
|
91 |
+
pre: bool = False,
|
92 |
+
each_item: bool = False,
|
93 |
+
always: bool = False,
|
94 |
+
check_fields: bool | None = None,
|
95 |
+
allow_reuse: bool = False,
|
96 |
+
) -> Callable[[_V1ValidatorType], _V1ValidatorType]:
|
97 |
+
"""Decorate methods on the class indicating that they should be used to validate fields.
|
98 |
+
|
99 |
+
Args:
|
100 |
+
__field (str): The first field the validator should be called on; this is separate
|
101 |
+
from `fields` to ensure an error is raised if you don't pass at least one.
|
102 |
+
*fields (str): Additional field(s) the validator should be called on.
|
103 |
+
pre (bool, optional): Whether this validator should be called before the standard
|
104 |
+
validators (else after). Defaults to False.
|
105 |
+
each_item (bool, optional): For complex objects (sets, lists etc.) whether to validate
|
106 |
+
individual elements rather than the whole object. Defaults to False.
|
107 |
+
always (bool, optional): Whether this method and other validators should be called even if
|
108 |
+
the value is missing. Defaults to False.
|
109 |
+
check_fields (bool | None, optional): Whether to check that the fields actually exist on the model.
|
110 |
+
Defaults to None.
|
111 |
+
allow_reuse (bool, optional): Whether to track and raise an error if another validator refers to
|
112 |
+
the decorated function. Defaults to False.
|
113 |
+
|
114 |
+
Returns:
|
115 |
+
Callable: A decorator that can be used to decorate a
|
116 |
+
function to be used as a validator.
|
117 |
+
"""
|
118 |
+
warn(
|
119 |
+
'Pydantic V1 style `@validator` validators are deprecated.'
|
120 |
+
' You should migrate to Pydantic V2 style `@field_validator` validators,'
|
121 |
+
' see the migration guide for more details',
|
122 |
+
DeprecationWarning,
|
123 |
+
stacklevel=2,
|
124 |
+
)
|
125 |
+
|
126 |
+
if allow_reuse is True: # pragma: no cover
|
127 |
+
warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning)
|
128 |
+
fields = tuple((__field, *fields))
|
129 |
+
if isinstance(fields[0], FunctionType):
|
130 |
+
raise PydanticUserError(
|
131 |
+
'`@validator` should be used with fields and keyword arguments, not bare. '
|
132 |
+
"E.g. usage should be `@validator('<field_name>', ...)`",
|
133 |
+
code='validator-no-fields',
|
134 |
+
)
|
135 |
+
elif not all(isinstance(field, str) for field in fields):
|
136 |
+
raise PydanticUserError(
|
137 |
+
'`@validator` fields should be passed as separate string args. '
|
138 |
+
"E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`",
|
139 |
+
code='validator-invalid-fields',
|
140 |
+
)
|
141 |
+
|
142 |
+
mode: Literal['before', 'after'] = 'before' if pre is True else 'after'
|
143 |
+
|
144 |
+
def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]:
|
145 |
+
if _decorators.is_instance_method_from_sig(f):
|
146 |
+
raise PydanticUserError(
|
147 |
+
'`@validator` cannot be applied to instance methods', code='validator-instance-method'
|
148 |
+
)
|
149 |
+
# auto apply the @classmethod decorator
|
150 |
+
f = _decorators.ensure_classmethod_based_on_signature(f)
|
151 |
+
wrap = _decorators_v1.make_generic_v1_field_validator
|
152 |
+
validator_wrapper_info = _decorators.ValidatorDecoratorInfo(
|
153 |
+
fields=fields,
|
154 |
+
mode=mode,
|
155 |
+
each_item=each_item,
|
156 |
+
always=always,
|
157 |
+
check_fields=check_fields,
|
158 |
+
)
|
159 |
+
return _decorators.PydanticDescriptorProxy(f, validator_wrapper_info, shim=wrap)
|
160 |
+
|
161 |
+
return dec # type: ignore[return-value]
|
162 |
+
|
163 |
+
|
164 |
+
@overload
|
165 |
+
def root_validator(
|
166 |
+
*,
|
167 |
+
# if you don't specify `pre` the default is `pre=False`
|
168 |
+
# which means you need to specify `skip_on_failure=True`
|
169 |
+
skip_on_failure: Literal[True],
|
170 |
+
allow_reuse: bool = ...,
|
171 |
+
) -> Callable[
|
172 |
+
[_V1RootValidatorFunctionType],
|
173 |
+
_V1RootValidatorFunctionType,
|
174 |
+
]:
|
175 |
+
...
|
176 |
+
|
177 |
+
|
178 |
+
@overload
|
179 |
+
def root_validator(
|
180 |
+
*,
|
181 |
+
# if you specify `pre=True` then you don't need to specify
|
182 |
+
# `skip_on_failure`, in fact it is not allowed as an argument!
|
183 |
+
pre: Literal[True],
|
184 |
+
allow_reuse: bool = ...,
|
185 |
+
) -> Callable[
|
186 |
+
[_V1RootValidatorFunctionType],
|
187 |
+
_V1RootValidatorFunctionType,
|
188 |
+
]:
|
189 |
+
...
|
190 |
+
|
191 |
+
|
192 |
+
@overload
|
193 |
+
def root_validator(
|
194 |
+
*,
|
195 |
+
# if you explicitly specify `pre=False` then you
|
196 |
+
# MUST specify `skip_on_failure=True`
|
197 |
+
pre: Literal[False],
|
198 |
+
skip_on_failure: Literal[True],
|
199 |
+
allow_reuse: bool = ...,
|
200 |
+
) -> Callable[
|
201 |
+
[_V1RootValidatorFunctionType],
|
202 |
+
_V1RootValidatorFunctionType,
|
203 |
+
]:
|
204 |
+
...
|
205 |
+
|
206 |
+
|
207 |
+
@deprecated(
|
208 |
+
'Pydantic V1 style `@root_validator` validators are deprecated.'
|
209 |
+
' You should migrate to Pydantic V2 style `@model_validator` validators,'
|
210 |
+
' see the migration guide for more details',
|
211 |
+
category=None,
|
212 |
+
)
|
213 |
+
def root_validator(
|
214 |
+
*__args,
|
215 |
+
pre: bool = False,
|
216 |
+
skip_on_failure: bool = False,
|
217 |
+
allow_reuse: bool = False,
|
218 |
+
) -> Any:
|
219 |
+
"""Decorate methods on a model indicating that they should be used to validate (and perhaps
|
220 |
+
modify) data either before or after standard model parsing/validation is performed.
|
221 |
+
|
222 |
+
Args:
|
223 |
+
pre (bool, optional): Whether this validator should be called before the standard
|
224 |
+
validators (else after). Defaults to False.
|
225 |
+
skip_on_failure (bool, optional): Whether to stop validation and return as soon as a
|
226 |
+
failure is encountered. Defaults to False.
|
227 |
+
allow_reuse (bool, optional): Whether to track and raise an error if another validator
|
228 |
+
refers to the decorated function. Defaults to False.
|
229 |
+
|
230 |
+
Returns:
|
231 |
+
Any: A decorator that can be used to decorate a function to be used as a root_validator.
|
232 |
+
"""
|
233 |
+
warn(
|
234 |
+
'Pydantic V1 style `@root_validator` validators are deprecated.'
|
235 |
+
' You should migrate to Pydantic V2 style `@model_validator` validators,'
|
236 |
+
' see the migration guide for more details',
|
237 |
+
DeprecationWarning,
|
238 |
+
stacklevel=2,
|
239 |
+
)
|
240 |
+
|
241 |
+
if __args:
|
242 |
+
# Ensure a nice error is raised if someone attempts to use the bare decorator
|
243 |
+
return root_validator()(*__args) # type: ignore
|
244 |
+
|
245 |
+
if allow_reuse is True: # pragma: no cover
|
246 |
+
warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning)
|
247 |
+
mode: Literal['before', 'after'] = 'before' if pre is True else 'after'
|
248 |
+
if pre is False and skip_on_failure is not True:
|
249 |
+
raise PydanticUserError(
|
250 |
+
'If you use `@root_validator` with pre=False (the default) you MUST specify `skip_on_failure=True`.'
|
251 |
+
' Note that `@root_validator` is deprecated and should be replaced with `@model_validator`.',
|
252 |
+
code='root-validator-pre-skip',
|
253 |
+
)
|
254 |
+
|
255 |
+
wrap = partial(_decorators_v1.make_v1_generic_root_validator, pre=pre)
|
256 |
+
|
257 |
+
def dec(f: Callable[..., Any] | classmethod[Any, Any, Any] | staticmethod[Any, Any]) -> Any:
|
258 |
+
if _decorators.is_instance_method_from_sig(f):
|
259 |
+
raise TypeError('`@root_validator` cannot be applied to instance methods')
|
260 |
+
# auto apply the @classmethod decorator
|
261 |
+
res = _decorators.ensure_classmethod_based_on_signature(f)
|
262 |
+
dec_info = _decorators.RootValidatorDecoratorInfo(mode=mode)
|
263 |
+
return _decorators.PydanticDescriptorProxy(res, dec_info, shim=wrap)
|
264 |
+
|
265 |
+
return dec
|
venv/lib/python3.10/site-packages/pydantic/deprecated/config.py
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations as _annotations
|
2 |
+
|
3 |
+
import warnings
|
4 |
+
from typing import TYPE_CHECKING, Any
|
5 |
+
|
6 |
+
from typing_extensions import Literal, 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 `pydantic.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 [`pydantic.ConfigDict`][pydantic.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 |
+
"`pydantic.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'
|
venv/lib/python3.10/site-packages/pydantic/deprecated/copy_internals.py
ADDED
@@ -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, Tuple
|
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.model_fields.items() if v.exclude is not None}, exclude
|
44 |
+
)
|
45 |
+
|
46 |
+
if include is not None:
|
47 |
+
include = _utils.ValueItems.merge({k: True for k in self.model_fields}, 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.model_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.model_fields:
|
79 |
+
dict_key = self.model_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: typing.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
|
venv/lib/python3.10/site-packages/pydantic/deprecated/decorator.py
ADDED
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import warnings
|
2 |
+
from functools import wraps
|
3 |
+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, TypeVar, Union, overload
|
4 |
+
|
5 |
+
from typing_extensions import deprecated
|
6 |
+
|
7 |
+
from .._internal import _config, _typing_extra
|
8 |
+
from ..alias_generators import to_pascal
|
9 |
+
from ..errors import PydanticUserError
|
10 |
+
from ..functional_validators import field_validator
|
11 |
+
from ..main import BaseModel, create_model
|
12 |
+
from ..warnings import PydanticDeprecatedSince20
|
13 |
+
|
14 |
+
if not TYPE_CHECKING:
|
15 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
16 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
17 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
18 |
+
|
19 |
+
__all__ = ('validate_arguments',)
|
20 |
+
|
21 |
+
if TYPE_CHECKING:
|
22 |
+
AnyCallable = Callable[..., Any]
|
23 |
+
|
24 |
+
AnyCallableT = TypeVar('AnyCallableT', bound=AnyCallable)
|
25 |
+
ConfigType = Union[None, Type[Any], Dict[str, Any]]
|
26 |
+
|
27 |
+
|
28 |
+
@overload
|
29 |
+
def validate_arguments(func: None = None, *, config: 'ConfigType' = None) -> Callable[['AnyCallableT'], 'AnyCallableT']:
|
30 |
+
...
|
31 |
+
|
32 |
+
|
33 |
+
@overload
|
34 |
+
def validate_arguments(func: 'AnyCallableT') -> 'AnyCallableT':
|
35 |
+
...
|
36 |
+
|
37 |
+
|
38 |
+
@deprecated(
|
39 |
+
'The `validate_arguments` method is deprecated; use `validate_call` instead.',
|
40 |
+
category=None,
|
41 |
+
)
|
42 |
+
def validate_arguments(func: Optional['AnyCallableT'] = None, *, config: 'ConfigType' = None) -> Any:
|
43 |
+
"""Decorator to validate the arguments passed to a function."""
|
44 |
+
warnings.warn(
|
45 |
+
'The `validate_arguments` method is deprecated; use `validate_call` instead.',
|
46 |
+
PydanticDeprecatedSince20,
|
47 |
+
stacklevel=2,
|
48 |
+
)
|
49 |
+
|
50 |
+
def validate(_func: 'AnyCallable') -> 'AnyCallable':
|
51 |
+
vd = ValidatedFunction(_func, config)
|
52 |
+
|
53 |
+
@wraps(_func)
|
54 |
+
def wrapper_function(*args: Any, **kwargs: Any) -> Any:
|
55 |
+
return vd.call(*args, **kwargs)
|
56 |
+
|
57 |
+
wrapper_function.vd = vd # type: ignore
|
58 |
+
wrapper_function.validate = vd.init_model_instance # type: ignore
|
59 |
+
wrapper_function.raw_function = vd.raw_function # type: ignore
|
60 |
+
wrapper_function.model = vd.model # type: ignore
|
61 |
+
return wrapper_function
|
62 |
+
|
63 |
+
if func:
|
64 |
+
return validate(func)
|
65 |
+
else:
|
66 |
+
return validate
|
67 |
+
|
68 |
+
|
69 |
+
ALT_V_ARGS = 'v__args'
|
70 |
+
ALT_V_KWARGS = 'v__kwargs'
|
71 |
+
V_POSITIONAL_ONLY_NAME = 'v__positional_only'
|
72 |
+
V_DUPLICATE_KWARGS = 'v__duplicate_kwargs'
|
73 |
+
|
74 |
+
|
75 |
+
class ValidatedFunction:
|
76 |
+
def __init__(self, function: 'AnyCallable', config: 'ConfigType'):
|
77 |
+
from inspect import Parameter, signature
|
78 |
+
|
79 |
+
parameters: Mapping[str, Parameter] = signature(function).parameters
|
80 |
+
|
81 |
+
if parameters.keys() & {ALT_V_ARGS, ALT_V_KWARGS, V_POSITIONAL_ONLY_NAME, V_DUPLICATE_KWARGS}:
|
82 |
+
raise PydanticUserError(
|
83 |
+
f'"{ALT_V_ARGS}", "{ALT_V_KWARGS}", "{V_POSITIONAL_ONLY_NAME}" and "{V_DUPLICATE_KWARGS}" '
|
84 |
+
f'are not permitted as argument names when using the "{validate_arguments.__name__}" decorator',
|
85 |
+
code=None,
|
86 |
+
)
|
87 |
+
|
88 |
+
self.raw_function = function
|
89 |
+
self.arg_mapping: Dict[int, str] = {}
|
90 |
+
self.positional_only_args: set[str] = set()
|
91 |
+
self.v_args_name = 'args'
|
92 |
+
self.v_kwargs_name = 'kwargs'
|
93 |
+
|
94 |
+
type_hints = _typing_extra.get_type_hints(function, include_extras=True)
|
95 |
+
takes_args = False
|
96 |
+
takes_kwargs = False
|
97 |
+
fields: Dict[str, Tuple[Any, Any]] = {}
|
98 |
+
for i, (name, p) in enumerate(parameters.items()):
|
99 |
+
if p.annotation is p.empty:
|
100 |
+
annotation = Any
|
101 |
+
else:
|
102 |
+
annotation = type_hints[name]
|
103 |
+
|
104 |
+
default = ... if p.default is p.empty else p.default
|
105 |
+
if p.kind == Parameter.POSITIONAL_ONLY:
|
106 |
+
self.arg_mapping[i] = name
|
107 |
+
fields[name] = annotation, default
|
108 |
+
fields[V_POSITIONAL_ONLY_NAME] = List[str], None
|
109 |
+
self.positional_only_args.add(name)
|
110 |
+
elif p.kind == Parameter.POSITIONAL_OR_KEYWORD:
|
111 |
+
self.arg_mapping[i] = name
|
112 |
+
fields[name] = annotation, default
|
113 |
+
fields[V_DUPLICATE_KWARGS] = List[str], None
|
114 |
+
elif p.kind == Parameter.KEYWORD_ONLY:
|
115 |
+
fields[name] = annotation, default
|
116 |
+
elif p.kind == Parameter.VAR_POSITIONAL:
|
117 |
+
self.v_args_name = name
|
118 |
+
fields[name] = Tuple[annotation, ...], None
|
119 |
+
takes_args = True
|
120 |
+
else:
|
121 |
+
assert p.kind == Parameter.VAR_KEYWORD, p.kind
|
122 |
+
self.v_kwargs_name = name
|
123 |
+
fields[name] = Dict[str, annotation], None
|
124 |
+
takes_kwargs = True
|
125 |
+
|
126 |
+
# these checks avoid a clash between "args" and a field with that name
|
127 |
+
if not takes_args and self.v_args_name in fields:
|
128 |
+
self.v_args_name = ALT_V_ARGS
|
129 |
+
|
130 |
+
# same with "kwargs"
|
131 |
+
if not takes_kwargs and self.v_kwargs_name in fields:
|
132 |
+
self.v_kwargs_name = ALT_V_KWARGS
|
133 |
+
|
134 |
+
if not takes_args:
|
135 |
+
# we add the field so validation below can raise the correct exception
|
136 |
+
fields[self.v_args_name] = List[Any], None
|
137 |
+
|
138 |
+
if not takes_kwargs:
|
139 |
+
# same with kwargs
|
140 |
+
fields[self.v_kwargs_name] = Dict[Any, Any], None
|
141 |
+
|
142 |
+
self.create_model(fields, takes_args, takes_kwargs, config)
|
143 |
+
|
144 |
+
def init_model_instance(self, *args: Any, **kwargs: Any) -> BaseModel:
|
145 |
+
values = self.build_values(args, kwargs)
|
146 |
+
return self.model(**values)
|
147 |
+
|
148 |
+
def call(self, *args: Any, **kwargs: Any) -> Any:
|
149 |
+
m = self.init_model_instance(*args, **kwargs)
|
150 |
+
return self.execute(m)
|
151 |
+
|
152 |
+
def build_values(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
153 |
+
values: Dict[str, Any] = {}
|
154 |
+
if args:
|
155 |
+
arg_iter = enumerate(args)
|
156 |
+
while True:
|
157 |
+
try:
|
158 |
+
i, a = next(arg_iter)
|
159 |
+
except StopIteration:
|
160 |
+
break
|
161 |
+
arg_name = self.arg_mapping.get(i)
|
162 |
+
if arg_name is not None:
|
163 |
+
values[arg_name] = a
|
164 |
+
else:
|
165 |
+
values[self.v_args_name] = [a] + [a for _, a in arg_iter]
|
166 |
+
break
|
167 |
+
|
168 |
+
var_kwargs: Dict[str, Any] = {}
|
169 |
+
wrong_positional_args = []
|
170 |
+
duplicate_kwargs = []
|
171 |
+
fields_alias = [
|
172 |
+
field.alias
|
173 |
+
for name, field in self.model.model_fields.items()
|
174 |
+
if name not in (self.v_args_name, self.v_kwargs_name)
|
175 |
+
]
|
176 |
+
non_var_fields = set(self.model.model_fields) - {self.v_args_name, self.v_kwargs_name}
|
177 |
+
for k, v in kwargs.items():
|
178 |
+
if k in non_var_fields or k in fields_alias:
|
179 |
+
if k in self.positional_only_args:
|
180 |
+
wrong_positional_args.append(k)
|
181 |
+
if k in values:
|
182 |
+
duplicate_kwargs.append(k)
|
183 |
+
values[k] = v
|
184 |
+
else:
|
185 |
+
var_kwargs[k] = v
|
186 |
+
|
187 |
+
if var_kwargs:
|
188 |
+
values[self.v_kwargs_name] = var_kwargs
|
189 |
+
if wrong_positional_args:
|
190 |
+
values[V_POSITIONAL_ONLY_NAME] = wrong_positional_args
|
191 |
+
if duplicate_kwargs:
|
192 |
+
values[V_DUPLICATE_KWARGS] = duplicate_kwargs
|
193 |
+
return values
|
194 |
+
|
195 |
+
def execute(self, m: BaseModel) -> Any:
|
196 |
+
d = {k: v for k, v in m.__dict__.items() if k in m.__pydantic_fields_set__ or m.model_fields[k].default_factory}
|
197 |
+
var_kwargs = d.pop(self.v_kwargs_name, {})
|
198 |
+
|
199 |
+
if self.v_args_name in d:
|
200 |
+
args_: List[Any] = []
|
201 |
+
in_kwargs = False
|
202 |
+
kwargs = {}
|
203 |
+
for name, value in d.items():
|
204 |
+
if in_kwargs:
|
205 |
+
kwargs[name] = value
|
206 |
+
elif name == self.v_args_name:
|
207 |
+
args_ += value
|
208 |
+
in_kwargs = True
|
209 |
+
else:
|
210 |
+
args_.append(value)
|
211 |
+
return self.raw_function(*args_, **kwargs, **var_kwargs)
|
212 |
+
elif self.positional_only_args:
|
213 |
+
args_ = []
|
214 |
+
kwargs = {}
|
215 |
+
for name, value in d.items():
|
216 |
+
if name in self.positional_only_args:
|
217 |
+
args_.append(value)
|
218 |
+
else:
|
219 |
+
kwargs[name] = value
|
220 |
+
return self.raw_function(*args_, **kwargs, **var_kwargs)
|
221 |
+
else:
|
222 |
+
return self.raw_function(**d, **var_kwargs)
|
223 |
+
|
224 |
+
def create_model(self, fields: Dict[str, Any], takes_args: bool, takes_kwargs: bool, config: 'ConfigType') -> None:
|
225 |
+
pos_args = len(self.arg_mapping)
|
226 |
+
|
227 |
+
config_wrapper = _config.ConfigWrapper(config)
|
228 |
+
|
229 |
+
if config_wrapper.alias_generator:
|
230 |
+
raise PydanticUserError(
|
231 |
+
'Setting the "alias_generator" property on custom Config for '
|
232 |
+
'@validate_arguments is not yet supported, please remove.',
|
233 |
+
code=None,
|
234 |
+
)
|
235 |
+
if config_wrapper.extra is None:
|
236 |
+
config_wrapper.config_dict['extra'] = 'forbid'
|
237 |
+
|
238 |
+
class DecoratorBaseModel(BaseModel):
|
239 |
+
@field_validator(self.v_args_name, check_fields=False)
|
240 |
+
@classmethod
|
241 |
+
def check_args(cls, v: Optional[List[Any]]) -> Optional[List[Any]]:
|
242 |
+
if takes_args or v is None:
|
243 |
+
return v
|
244 |
+
|
245 |
+
raise TypeError(f'{pos_args} positional arguments expected but {pos_args + len(v)} given')
|
246 |
+
|
247 |
+
@field_validator(self.v_kwargs_name, check_fields=False)
|
248 |
+
@classmethod
|
249 |
+
def check_kwargs(cls, v: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
250 |
+
if takes_kwargs or v is None:
|
251 |
+
return v
|
252 |
+
|
253 |
+
plural = '' if len(v) == 1 else 's'
|
254 |
+
keys = ', '.join(map(repr, v.keys()))
|
255 |
+
raise TypeError(f'unexpected keyword argument{plural}: {keys}')
|
256 |
+
|
257 |
+
@field_validator(V_POSITIONAL_ONLY_NAME, check_fields=False)
|
258 |
+
@classmethod
|
259 |
+
def check_positional_only(cls, v: Optional[List[str]]) -> None:
|
260 |
+
if v is None:
|
261 |
+
return
|
262 |
+
|
263 |
+
plural = '' if len(v) == 1 else 's'
|
264 |
+
keys = ', '.join(map(repr, v))
|
265 |
+
raise TypeError(f'positional-only argument{plural} passed as keyword argument{plural}: {keys}')
|
266 |
+
|
267 |
+
@field_validator(V_DUPLICATE_KWARGS, check_fields=False)
|
268 |
+
@classmethod
|
269 |
+
def check_duplicate_kwargs(cls, v: Optional[List[str]]) -> None:
|
270 |
+
if v is None:
|
271 |
+
return
|
272 |
+
|
273 |
+
plural = '' if len(v) == 1 else 's'
|
274 |
+
keys = ', '.join(map(repr, v))
|
275 |
+
raise TypeError(f'multiple values for argument{plural}: {keys}')
|
276 |
+
|
277 |
+
model_config = config_wrapper.config_dict
|
278 |
+
|
279 |
+
self.model = create_model(to_pascal(self.raw_function.__name__), __base__=DecoratorBaseModel, **fields)
|
venv/lib/python3.10/site-packages/pydantic/deprecated/json.py
ADDED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime
|
2 |
+
import warnings
|
3 |
+
from collections import deque
|
4 |
+
from decimal import Decimal
|
5 |
+
from enum import Enum
|
6 |
+
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
|
7 |
+
from pathlib import Path
|
8 |
+
from re import Pattern
|
9 |
+
from types import GeneratorType
|
10 |
+
from typing import TYPE_CHECKING, Any, Callable, Dict, Type, Union
|
11 |
+
from uuid import UUID
|
12 |
+
|
13 |
+
from typing_extensions import deprecated
|
14 |
+
|
15 |
+
from ..color import Color
|
16 |
+
from ..networks import NameEmail
|
17 |
+
from ..types import SecretBytes, SecretStr
|
18 |
+
from ..warnings import PydanticDeprecatedSince20
|
19 |
+
|
20 |
+
if not TYPE_CHECKING:
|
21 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
22 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
23 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
24 |
+
|
25 |
+
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
|
26 |
+
|
27 |
+
|
28 |
+
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
|
29 |
+
return o.isoformat()
|
30 |
+
|
31 |
+
|
32 |
+
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
|
33 |
+
"""Encodes a Decimal as int of there's no exponent, otherwise float.
|
34 |
+
|
35 |
+
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
|
36 |
+
where a integer (but not int typed) is used. Encoding this as a float
|
37 |
+
results in failed round-tripping between encode and parse.
|
38 |
+
Our Id type is a prime example of this.
|
39 |
+
|
40 |
+
>>> decimal_encoder(Decimal("1.0"))
|
41 |
+
1.0
|
42 |
+
|
43 |
+
>>> decimal_encoder(Decimal("1"))
|
44 |
+
1
|
45 |
+
"""
|
46 |
+
exponent = dec_value.as_tuple().exponent
|
47 |
+
if isinstance(exponent, int) and exponent >= 0:
|
48 |
+
return int(dec_value)
|
49 |
+
else:
|
50 |
+
return float(dec_value)
|
51 |
+
|
52 |
+
|
53 |
+
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
|
54 |
+
bytes: lambda o: o.decode(),
|
55 |
+
Color: str,
|
56 |
+
datetime.date: isoformat,
|
57 |
+
datetime.datetime: isoformat,
|
58 |
+
datetime.time: isoformat,
|
59 |
+
datetime.timedelta: lambda td: td.total_seconds(),
|
60 |
+
Decimal: decimal_encoder,
|
61 |
+
Enum: lambda o: o.value,
|
62 |
+
frozenset: list,
|
63 |
+
deque: list,
|
64 |
+
GeneratorType: list,
|
65 |
+
IPv4Address: str,
|
66 |
+
IPv4Interface: str,
|
67 |
+
IPv4Network: str,
|
68 |
+
IPv6Address: str,
|
69 |
+
IPv6Interface: str,
|
70 |
+
IPv6Network: str,
|
71 |
+
NameEmail: str,
|
72 |
+
Path: str,
|
73 |
+
Pattern: lambda o: o.pattern,
|
74 |
+
SecretBytes: str,
|
75 |
+
SecretStr: str,
|
76 |
+
set: list,
|
77 |
+
UUID: str,
|
78 |
+
}
|
79 |
+
|
80 |
+
|
81 |
+
@deprecated(
|
82 |
+
'`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.',
|
83 |
+
category=None,
|
84 |
+
)
|
85 |
+
def pydantic_encoder(obj: Any) -> Any:
|
86 |
+
warnings.warn(
|
87 |
+
'`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.',
|
88 |
+
category=PydanticDeprecatedSince20,
|
89 |
+
stacklevel=2,
|
90 |
+
)
|
91 |
+
from dataclasses import asdict, is_dataclass
|
92 |
+
|
93 |
+
from ..main import BaseModel
|
94 |
+
|
95 |
+
if isinstance(obj, BaseModel):
|
96 |
+
return obj.model_dump()
|
97 |
+
elif is_dataclass(obj):
|
98 |
+
return asdict(obj)
|
99 |
+
|
100 |
+
# Check the class type and its superclasses for a matching encoder
|
101 |
+
for base in obj.__class__.__mro__[:-1]:
|
102 |
+
try:
|
103 |
+
encoder = ENCODERS_BY_TYPE[base]
|
104 |
+
except KeyError:
|
105 |
+
continue
|
106 |
+
return encoder(obj)
|
107 |
+
else: # We have exited the for loop without finding a suitable encoder
|
108 |
+
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
|
109 |
+
|
110 |
+
|
111 |
+
# TODO: Add a suggested migration path once there is a way to use custom encoders
|
112 |
+
@deprecated(
|
113 |
+
'`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.',
|
114 |
+
category=None,
|
115 |
+
)
|
116 |
+
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
|
117 |
+
warnings.warn(
|
118 |
+
'`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.',
|
119 |
+
category=PydanticDeprecatedSince20,
|
120 |
+
stacklevel=2,
|
121 |
+
)
|
122 |
+
# Check the class type and its superclasses for a matching encoder
|
123 |
+
for base in obj.__class__.__mro__[:-1]:
|
124 |
+
try:
|
125 |
+
encoder = type_encoders[base]
|
126 |
+
except KeyError:
|
127 |
+
continue
|
128 |
+
|
129 |
+
return encoder(obj)
|
130 |
+
else: # We have exited the for loop without finding a suitable encoder
|
131 |
+
return pydantic_encoder(obj)
|
132 |
+
|
133 |
+
|
134 |
+
@deprecated('`timedelta_isoformat` is deprecated.', category=None)
|
135 |
+
def timedelta_isoformat(td: datetime.timedelta) -> str:
|
136 |
+
"""ISO 8601 encoding for Python timedelta object."""
|
137 |
+
warnings.warn('`timedelta_isoformat` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
138 |
+
minutes, seconds = divmod(td.seconds, 60)
|
139 |
+
hours, minutes = divmod(minutes, 60)
|
140 |
+
return f'{"-" if td.days < 0 else ""}P{abs(td.days)}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
|
venv/lib/python3.10/site-packages/pydantic/deprecated/parse.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import json
|
4 |
+
import pickle
|
5 |
+
import warnings
|
6 |
+
from enum import Enum
|
7 |
+
from pathlib import Path
|
8 |
+
from typing import TYPE_CHECKING, Any, Callable
|
9 |
+
|
10 |
+
from typing_extensions import deprecated
|
11 |
+
|
12 |
+
from ..warnings import PydanticDeprecatedSince20
|
13 |
+
|
14 |
+
if not TYPE_CHECKING:
|
15 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
16 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
17 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
18 |
+
|
19 |
+
|
20 |
+
class Protocol(str, Enum):
|
21 |
+
json = 'json'
|
22 |
+
pickle = 'pickle'
|
23 |
+
|
24 |
+
|
25 |
+
@deprecated('`load_str_bytes` is deprecated.', category=None)
|
26 |
+
def load_str_bytes(
|
27 |
+
b: str | bytes,
|
28 |
+
*,
|
29 |
+
content_type: str | None = None,
|
30 |
+
encoding: str = 'utf8',
|
31 |
+
proto: Protocol | None = None,
|
32 |
+
allow_pickle: bool = False,
|
33 |
+
json_loads: Callable[[str], Any] = json.loads,
|
34 |
+
) -> Any:
|
35 |
+
warnings.warn('`load_str_bytes` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
36 |
+
if proto is None and content_type:
|
37 |
+
if content_type.endswith(('json', 'javascript')):
|
38 |
+
pass
|
39 |
+
elif allow_pickle and content_type.endswith('pickle'):
|
40 |
+
proto = Protocol.pickle
|
41 |
+
else:
|
42 |
+
raise TypeError(f'Unknown content-type: {content_type}')
|
43 |
+
|
44 |
+
proto = proto or Protocol.json
|
45 |
+
|
46 |
+
if proto == Protocol.json:
|
47 |
+
if isinstance(b, bytes):
|
48 |
+
b = b.decode(encoding)
|
49 |
+
return json_loads(b) # type: ignore
|
50 |
+
elif proto == Protocol.pickle:
|
51 |
+
if not allow_pickle:
|
52 |
+
raise RuntimeError('Trying to decode with pickle with allow_pickle=False')
|
53 |
+
bb = b if isinstance(b, bytes) else b.encode() # type: ignore
|
54 |
+
return pickle.loads(bb)
|
55 |
+
else:
|
56 |
+
raise TypeError(f'Unknown protocol: {proto}')
|
57 |
+
|
58 |
+
|
59 |
+
@deprecated('`load_file` is deprecated.', category=None)
|
60 |
+
def load_file(
|
61 |
+
path: str | Path,
|
62 |
+
*,
|
63 |
+
content_type: str | None = None,
|
64 |
+
encoding: str = 'utf8',
|
65 |
+
proto: Protocol | None = None,
|
66 |
+
allow_pickle: bool = False,
|
67 |
+
json_loads: Callable[[str], Any] = json.loads,
|
68 |
+
) -> Any:
|
69 |
+
warnings.warn('`load_file` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
70 |
+
path = Path(path)
|
71 |
+
b = path.read_bytes()
|
72 |
+
if content_type is None:
|
73 |
+
if path.suffix in ('.js', '.json'):
|
74 |
+
proto = Protocol.json
|
75 |
+
elif path.suffix == '.pkl':
|
76 |
+
proto = Protocol.pickle
|
77 |
+
|
78 |
+
return load_str_bytes(
|
79 |
+
b, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle, json_loads=json_loads
|
80 |
+
)
|
venv/lib/python3.10/site-packages/pydantic/deprecated/tools.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import json
|
4 |
+
import warnings
|
5 |
+
from typing import TYPE_CHECKING, Any, Callable, Type, TypeVar, Union
|
6 |
+
|
7 |
+
from typing_extensions import deprecated
|
8 |
+
|
9 |
+
from ..json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema
|
10 |
+
from ..type_adapter import TypeAdapter
|
11 |
+
from ..warnings import PydanticDeprecatedSince20
|
12 |
+
|
13 |
+
if not TYPE_CHECKING:
|
14 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
15 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
16 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
17 |
+
|
18 |
+
__all__ = 'parse_obj_as', 'schema_of', 'schema_json_of'
|
19 |
+
|
20 |
+
NameFactory = Union[str, Callable[[Type[Any]], str]]
|
21 |
+
|
22 |
+
|
23 |
+
T = TypeVar('T')
|
24 |
+
|
25 |
+
|
26 |
+
@deprecated(
|
27 |
+
'`parse_obj_as` is deprecated. Use `pydantic.TypeAdapter.validate_python` instead.',
|
28 |
+
category=None,
|
29 |
+
)
|
30 |
+
def parse_obj_as(type_: type[T], obj: Any, type_name: NameFactory | None = None) -> T:
|
31 |
+
warnings.warn(
|
32 |
+
'`parse_obj_as` is deprecated. Use `pydantic.TypeAdapter.validate_python` instead.',
|
33 |
+
category=PydanticDeprecatedSince20,
|
34 |
+
stacklevel=2,
|
35 |
+
)
|
36 |
+
if type_name is not None: # pragma: no cover
|
37 |
+
warnings.warn(
|
38 |
+
'The type_name parameter is deprecated. parse_obj_as no longer creates temporary models',
|
39 |
+
DeprecationWarning,
|
40 |
+
stacklevel=2,
|
41 |
+
)
|
42 |
+
return TypeAdapter(type_).validate_python(obj)
|
43 |
+
|
44 |
+
|
45 |
+
@deprecated(
|
46 |
+
'`schema_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
47 |
+
category=None,
|
48 |
+
)
|
49 |
+
def schema_of(
|
50 |
+
type_: Any,
|
51 |
+
*,
|
52 |
+
title: NameFactory | None = None,
|
53 |
+
by_alias: bool = True,
|
54 |
+
ref_template: str = DEFAULT_REF_TEMPLATE,
|
55 |
+
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
|
56 |
+
) -> dict[str, Any]:
|
57 |
+
"""Generate a JSON schema (as dict) for the passed model or dynamically generated one."""
|
58 |
+
warnings.warn(
|
59 |
+
'`schema_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
60 |
+
category=PydanticDeprecatedSince20,
|
61 |
+
stacklevel=2,
|
62 |
+
)
|
63 |
+
res = TypeAdapter(type_).json_schema(
|
64 |
+
by_alias=by_alias,
|
65 |
+
schema_generator=schema_generator,
|
66 |
+
ref_template=ref_template,
|
67 |
+
)
|
68 |
+
if title is not None:
|
69 |
+
if isinstance(title, str):
|
70 |
+
res['title'] = title
|
71 |
+
else:
|
72 |
+
warnings.warn(
|
73 |
+
'Passing a callable for the `title` parameter is deprecated and no longer supported',
|
74 |
+
DeprecationWarning,
|
75 |
+
stacklevel=2,
|
76 |
+
)
|
77 |
+
res['title'] = title(type_)
|
78 |
+
return res
|
79 |
+
|
80 |
+
|
81 |
+
@deprecated(
|
82 |
+
'`schema_json_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
83 |
+
category=None,
|
84 |
+
)
|
85 |
+
def schema_json_of(
|
86 |
+
type_: Any,
|
87 |
+
*,
|
88 |
+
title: NameFactory | None = None,
|
89 |
+
by_alias: bool = True,
|
90 |
+
ref_template: str = DEFAULT_REF_TEMPLATE,
|
91 |
+
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
|
92 |
+
**dumps_kwargs: Any,
|
93 |
+
) -> str:
|
94 |
+
"""Generate a JSON schema (as JSON) for the passed model or dynamically generated one."""
|
95 |
+
warnings.warn(
|
96 |
+
'`schema_json_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
97 |
+
category=PydanticDeprecatedSince20,
|
98 |
+
stacklevel=2,
|
99 |
+
)
|
100 |
+
return json.dumps(
|
101 |
+
schema_of(type_, title=title, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator),
|
102 |
+
**dumps_kwargs,
|
103 |
+
)
|
venv/lib/python3.10/site-packages/pydantic/plugin/__init__.py
ADDED
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Usage docs: https://docs.pydantic.dev/2.7/concepts/plugins#build-a-plugin
|
2 |
+
|
3 |
+
Plugin interface for Pydantic plugins, and related types.
|
4 |
+
"""
|
5 |
+
from __future__ import annotations
|
6 |
+
|
7 |
+
from typing import Any, Callable, NamedTuple
|
8 |
+
|
9 |
+
from pydantic_core import CoreConfig, CoreSchema, ValidationError
|
10 |
+
from typing_extensions import Literal, Protocol, TypeAlias
|
11 |
+
|
12 |
+
__all__ = (
|
13 |
+
'PydanticPluginProtocol',
|
14 |
+
'BaseValidateHandlerProtocol',
|
15 |
+
'ValidatePythonHandlerProtocol',
|
16 |
+
'ValidateJsonHandlerProtocol',
|
17 |
+
'ValidateStringsHandlerProtocol',
|
18 |
+
'NewSchemaReturns',
|
19 |
+
'SchemaTypePath',
|
20 |
+
'SchemaKind',
|
21 |
+
)
|
22 |
+
|
23 |
+
NewSchemaReturns: TypeAlias = 'tuple[ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None]'
|
24 |
+
|
25 |
+
|
26 |
+
class SchemaTypePath(NamedTuple):
|
27 |
+
"""Path defining where `schema_type` was defined, or where `TypeAdapter` was called."""
|
28 |
+
|
29 |
+
module: str
|
30 |
+
name: str
|
31 |
+
|
32 |
+
|
33 |
+
SchemaKind: TypeAlias = Literal['BaseModel', 'TypeAdapter', 'dataclass', 'create_model', 'validate_call']
|
34 |
+
|
35 |
+
|
36 |
+
class PydanticPluginProtocol(Protocol):
|
37 |
+
"""Protocol defining the interface for Pydantic plugins."""
|
38 |
+
|
39 |
+
def new_schema_validator(
|
40 |
+
self,
|
41 |
+
schema: CoreSchema,
|
42 |
+
schema_type: Any,
|
43 |
+
schema_type_path: SchemaTypePath,
|
44 |
+
schema_kind: SchemaKind,
|
45 |
+
config: CoreConfig | None,
|
46 |
+
plugin_settings: dict[str, object],
|
47 |
+
) -> tuple[
|
48 |
+
ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None
|
49 |
+
]:
|
50 |
+
"""This method is called for each plugin every time a new [`SchemaValidator`][pydantic_core.SchemaValidator]
|
51 |
+
is created.
|
52 |
+
|
53 |
+
It should return an event handler for each of the three validation methods, or `None` if the plugin does not
|
54 |
+
implement that method.
|
55 |
+
|
56 |
+
Args:
|
57 |
+
schema: The schema to validate against.
|
58 |
+
schema_type: The original type which the schema was created from, e.g. the model class.
|
59 |
+
schema_type_path: Path defining where `schema_type` was defined, or where `TypeAdapter` was called.
|
60 |
+
schema_kind: The kind of schema to validate against.
|
61 |
+
config: The config to use for validation.
|
62 |
+
plugin_settings: Any plugin settings.
|
63 |
+
|
64 |
+
Returns:
|
65 |
+
A tuple of optional event handlers for each of the three validation methods -
|
66 |
+
`validate_python`, `validate_json`, `validate_strings`.
|
67 |
+
"""
|
68 |
+
raise NotImplementedError('Pydantic plugins should implement `new_schema_validator`.')
|
69 |
+
|
70 |
+
|
71 |
+
class BaseValidateHandlerProtocol(Protocol):
|
72 |
+
"""Base class for plugin callbacks protocols.
|
73 |
+
|
74 |
+
You shouldn't implement this protocol directly, instead use one of the subclasses with adds the correctly
|
75 |
+
typed `on_error` method.
|
76 |
+
"""
|
77 |
+
|
78 |
+
on_enter: Callable[..., None]
|
79 |
+
"""`on_enter` is changed to be more specific on all subclasses"""
|
80 |
+
|
81 |
+
def on_success(self, result: Any) -> None:
|
82 |
+
"""Callback to be notified of successful validation.
|
83 |
+
|
84 |
+
Args:
|
85 |
+
result: The result of the validation.
|
86 |
+
"""
|
87 |
+
return
|
88 |
+
|
89 |
+
def on_error(self, error: ValidationError) -> None:
|
90 |
+
"""Callback to be notified of validation errors.
|
91 |
+
|
92 |
+
Args:
|
93 |
+
error: The validation error.
|
94 |
+
"""
|
95 |
+
return
|
96 |
+
|
97 |
+
def on_exception(self, exception: Exception) -> None:
|
98 |
+
"""Callback to be notified of validation exceptions.
|
99 |
+
|
100 |
+
Args:
|
101 |
+
exception: The exception raised during validation.
|
102 |
+
"""
|
103 |
+
return
|
104 |
+
|
105 |
+
|
106 |
+
class ValidatePythonHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
|
107 |
+
"""Event handler for `SchemaValidator.validate_python`."""
|
108 |
+
|
109 |
+
def on_enter(
|
110 |
+
self,
|
111 |
+
input: Any,
|
112 |
+
*,
|
113 |
+
strict: bool | None = None,
|
114 |
+
from_attributes: bool | None = None,
|
115 |
+
context: dict[str, Any] | None = None,
|
116 |
+
self_instance: Any | None = None,
|
117 |
+
) -> None:
|
118 |
+
"""Callback to be notified of validation start, and create an instance of the event handler.
|
119 |
+
|
120 |
+
Args:
|
121 |
+
input: The input to be validated.
|
122 |
+
strict: Whether to validate the object in strict mode.
|
123 |
+
from_attributes: Whether to validate objects as inputs by extracting attributes.
|
124 |
+
context: The context to use for validation, this is passed to functional validators.
|
125 |
+
self_instance: An instance of a model to set attributes on from validation, this is used when running
|
126 |
+
validation from the `__init__` method of a model.
|
127 |
+
"""
|
128 |
+
pass
|
129 |
+
|
130 |
+
|
131 |
+
class ValidateJsonHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
|
132 |
+
"""Event handler for `SchemaValidator.validate_json`."""
|
133 |
+
|
134 |
+
def on_enter(
|
135 |
+
self,
|
136 |
+
input: str | bytes | bytearray,
|
137 |
+
*,
|
138 |
+
strict: bool | None = None,
|
139 |
+
context: dict[str, Any] | None = None,
|
140 |
+
self_instance: Any | None = None,
|
141 |
+
) -> None:
|
142 |
+
"""Callback to be notified of validation start, and create an instance of the event handler.
|
143 |
+
|
144 |
+
Args:
|
145 |
+
input: The JSON data to be validated.
|
146 |
+
strict: Whether to validate the object in strict mode.
|
147 |
+
context: The context to use for validation, this is passed to functional validators.
|
148 |
+
self_instance: An instance of a model to set attributes on from validation, this is used when running
|
149 |
+
validation from the `__init__` method of a model.
|
150 |
+
"""
|
151 |
+
pass
|
152 |
+
|
153 |
+
|
154 |
+
StringInput: TypeAlias = 'dict[str, StringInput]'
|
155 |
+
|
156 |
+
|
157 |
+
class ValidateStringsHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
|
158 |
+
"""Event handler for `SchemaValidator.validate_strings`."""
|
159 |
+
|
160 |
+
def on_enter(
|
161 |
+
self, input: StringInput, *, strict: bool | None = None, context: dict[str, Any] | None = None
|
162 |
+
) -> None:
|
163 |
+
"""Callback to be notified of validation start, and create an instance of the event handler.
|
164 |
+
|
165 |
+
Args:
|
166 |
+
input: The string data to be validated.
|
167 |
+
strict: Whether to validate the object in strict mode.
|
168 |
+
context: The context to use for validation, this is passed to functional validators.
|
169 |
+
"""
|
170 |
+
pass
|
venv/lib/python3.10/site-packages/pydantic/plugin/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (7.31 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/plugin/__pycache__/_loader.cpython-310.pyc
ADDED
Binary file (1.6 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/plugin/__pycache__/_schema_validator.cpython-310.pyc
ADDED
Binary file (4.9 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/plugin/_loader.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import importlib.metadata as importlib_metadata
|
4 |
+
import os
|
5 |
+
import warnings
|
6 |
+
from typing import TYPE_CHECKING, Final, Iterable
|
7 |
+
|
8 |
+
if TYPE_CHECKING:
|
9 |
+
from . import PydanticPluginProtocol
|
10 |
+
|
11 |
+
|
12 |
+
PYDANTIC_ENTRY_POINT_GROUP: Final[str] = 'pydantic'
|
13 |
+
|
14 |
+
# cache of plugins
|
15 |
+
_plugins: dict[str, PydanticPluginProtocol] | None = None
|
16 |
+
# return no plugins while loading plugins to avoid recursion and errors while import plugins
|
17 |
+
# this means that if plugins use pydantic
|
18 |
+
_loading_plugins: bool = False
|
19 |
+
|
20 |
+
|
21 |
+
def get_plugins() -> Iterable[PydanticPluginProtocol]:
|
22 |
+
"""Load plugins for Pydantic.
|
23 |
+
|
24 |
+
Inspired by: https://github.com/pytest-dev/pluggy/blob/1.3.0/src/pluggy/_manager.py#L376-L402
|
25 |
+
"""
|
26 |
+
disabled_plugins = os.getenv('PYDANTIC_DISABLE_PLUGINS')
|
27 |
+
global _plugins, _loading_plugins
|
28 |
+
if _loading_plugins:
|
29 |
+
# this happens when plugins themselves use pydantic, we return no plugins
|
30 |
+
return ()
|
31 |
+
elif disabled_plugins in ('__all__', '1', 'true'):
|
32 |
+
return ()
|
33 |
+
elif _plugins is None:
|
34 |
+
_plugins = {}
|
35 |
+
# set _loading_plugins so any plugins that use pydantic don't themselves use plugins
|
36 |
+
_loading_plugins = True
|
37 |
+
try:
|
38 |
+
for dist in importlib_metadata.distributions():
|
39 |
+
for entry_point in dist.entry_points:
|
40 |
+
if entry_point.group != PYDANTIC_ENTRY_POINT_GROUP:
|
41 |
+
continue
|
42 |
+
if entry_point.value in _plugins:
|
43 |
+
continue
|
44 |
+
if disabled_plugins is not None and entry_point.name in disabled_plugins.split(','):
|
45 |
+
continue
|
46 |
+
try:
|
47 |
+
_plugins[entry_point.value] = entry_point.load()
|
48 |
+
except (ImportError, AttributeError) as e:
|
49 |
+
warnings.warn(
|
50 |
+
f'{e.__class__.__name__} while loading the `{entry_point.name}` Pydantic plugin, '
|
51 |
+
f'this plugin will not be installed.\n\n{e!r}'
|
52 |
+
)
|
53 |
+
finally:
|
54 |
+
_loading_plugins = False
|
55 |
+
|
56 |
+
return _plugins.values()
|
venv/lib/python3.10/site-packages/pydantic/plugin/_schema_validator.py
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Pluggable schema validator for pydantic."""
|
2 |
+
from __future__ import annotations
|
3 |
+
|
4 |
+
import functools
|
5 |
+
from typing import TYPE_CHECKING, Any, Callable, Iterable, TypeVar
|
6 |
+
|
7 |
+
from pydantic_core import CoreConfig, CoreSchema, SchemaValidator, ValidationError
|
8 |
+
from typing_extensions import Literal, ParamSpec
|
9 |
+
|
10 |
+
if TYPE_CHECKING:
|
11 |
+
from . import BaseValidateHandlerProtocol, PydanticPluginProtocol, SchemaKind, SchemaTypePath
|
12 |
+
|
13 |
+
|
14 |
+
P = ParamSpec('P')
|
15 |
+
R = TypeVar('R')
|
16 |
+
Event = Literal['on_validate_python', 'on_validate_json', 'on_validate_strings']
|
17 |
+
events: list[Event] = list(Event.__args__) # type: ignore
|
18 |
+
|
19 |
+
|
20 |
+
def create_schema_validator(
|
21 |
+
schema: CoreSchema,
|
22 |
+
schema_type: Any,
|
23 |
+
schema_type_module: str,
|
24 |
+
schema_type_name: str,
|
25 |
+
schema_kind: SchemaKind,
|
26 |
+
config: CoreConfig | None = None,
|
27 |
+
plugin_settings: dict[str, Any] | None = None,
|
28 |
+
) -> SchemaValidator:
|
29 |
+
"""Create a `SchemaValidator` or `PluggableSchemaValidator` if plugins are installed.
|
30 |
+
|
31 |
+
Returns:
|
32 |
+
If plugins are installed then return `PluggableSchemaValidator`, otherwise return `SchemaValidator`.
|
33 |
+
"""
|
34 |
+
from . import SchemaTypePath
|
35 |
+
from ._loader import get_plugins
|
36 |
+
|
37 |
+
plugins = get_plugins()
|
38 |
+
if plugins:
|
39 |
+
return PluggableSchemaValidator(
|
40 |
+
schema,
|
41 |
+
schema_type,
|
42 |
+
SchemaTypePath(schema_type_module, schema_type_name),
|
43 |
+
schema_kind,
|
44 |
+
config,
|
45 |
+
plugins,
|
46 |
+
plugin_settings or {},
|
47 |
+
) # type: ignore
|
48 |
+
else:
|
49 |
+
return SchemaValidator(schema, config)
|
50 |
+
|
51 |
+
|
52 |
+
class PluggableSchemaValidator:
|
53 |
+
"""Pluggable schema validator."""
|
54 |
+
|
55 |
+
__slots__ = '_schema_validator', 'validate_json', 'validate_python', 'validate_strings'
|
56 |
+
|
57 |
+
def __init__(
|
58 |
+
self,
|
59 |
+
schema: CoreSchema,
|
60 |
+
schema_type: Any,
|
61 |
+
schema_type_path: SchemaTypePath,
|
62 |
+
schema_kind: SchemaKind,
|
63 |
+
config: CoreConfig | None,
|
64 |
+
plugins: Iterable[PydanticPluginProtocol],
|
65 |
+
plugin_settings: dict[str, Any],
|
66 |
+
) -> None:
|
67 |
+
self._schema_validator = SchemaValidator(schema, config)
|
68 |
+
|
69 |
+
python_event_handlers: list[BaseValidateHandlerProtocol] = []
|
70 |
+
json_event_handlers: list[BaseValidateHandlerProtocol] = []
|
71 |
+
strings_event_handlers: list[BaseValidateHandlerProtocol] = []
|
72 |
+
for plugin in plugins:
|
73 |
+
try:
|
74 |
+
p, j, s = plugin.new_schema_validator(
|
75 |
+
schema, schema_type, schema_type_path, schema_kind, config, plugin_settings
|
76 |
+
)
|
77 |
+
except TypeError as e: # pragma: no cover
|
78 |
+
raise TypeError(f'Error using plugin `{plugin.__module__}:{plugin.__class__.__name__}`: {e}') from e
|
79 |
+
if p is not None:
|
80 |
+
python_event_handlers.append(p)
|
81 |
+
if j is not None:
|
82 |
+
json_event_handlers.append(j)
|
83 |
+
if s is not None:
|
84 |
+
strings_event_handlers.append(s)
|
85 |
+
|
86 |
+
self.validate_python = build_wrapper(self._schema_validator.validate_python, python_event_handlers)
|
87 |
+
self.validate_json = build_wrapper(self._schema_validator.validate_json, json_event_handlers)
|
88 |
+
self.validate_strings = build_wrapper(self._schema_validator.validate_strings, strings_event_handlers)
|
89 |
+
|
90 |
+
def __getattr__(self, name: str) -> Any:
|
91 |
+
return getattr(self._schema_validator, name)
|
92 |
+
|
93 |
+
|
94 |
+
def build_wrapper(func: Callable[P, R], event_handlers: list[BaseValidateHandlerProtocol]) -> Callable[P, R]:
|
95 |
+
if not event_handlers:
|
96 |
+
return func
|
97 |
+
else:
|
98 |
+
on_enters = tuple(h.on_enter for h in event_handlers if filter_handlers(h, 'on_enter'))
|
99 |
+
on_successes = tuple(h.on_success for h in event_handlers if filter_handlers(h, 'on_success'))
|
100 |
+
on_errors = tuple(h.on_error for h in event_handlers if filter_handlers(h, 'on_error'))
|
101 |
+
on_exceptions = tuple(h.on_exception for h in event_handlers if filter_handlers(h, 'on_exception'))
|
102 |
+
|
103 |
+
@functools.wraps(func)
|
104 |
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
105 |
+
for on_enter_handler in on_enters:
|
106 |
+
on_enter_handler(*args, **kwargs)
|
107 |
+
|
108 |
+
try:
|
109 |
+
result = func(*args, **kwargs)
|
110 |
+
except ValidationError as error:
|
111 |
+
for on_error_handler in on_errors:
|
112 |
+
on_error_handler(error)
|
113 |
+
raise
|
114 |
+
except Exception as exception:
|
115 |
+
for on_exception_handler in on_exceptions:
|
116 |
+
on_exception_handler(exception)
|
117 |
+
raise
|
118 |
+
else:
|
119 |
+
for on_success_handler in on_successes:
|
120 |
+
on_success_handler(result)
|
121 |
+
return result
|
122 |
+
|
123 |
+
return wrapper
|
124 |
+
|
125 |
+
|
126 |
+
def filter_handlers(handler_cls: BaseValidateHandlerProtocol, method_name: str) -> bool:
|
127 |
+
"""Filter out handler methods which are not implemented by the plugin directly - e.g. are missing
|
128 |
+
or are inherited from the protocol.
|
129 |
+
"""
|
130 |
+
handler = getattr(handler_cls, method_name, None)
|
131 |
+
if handler is None:
|
132 |
+
return False
|
133 |
+
elif handler.__module__ == 'pydantic.plugin':
|
134 |
+
# this is the original handler, from the protocol due to runtime inheritance
|
135 |
+
# we don't want to call it
|
136 |
+
return False
|
137 |
+
else:
|
138 |
+
return True
|
venv/lib/python3.10/site-packages/pydantic/v1/__init__.py
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# flake8: noqa
|
2 |
+
from . import dataclasses
|
3 |
+
from .annotated_types import create_model_from_namedtuple, create_model_from_typeddict
|
4 |
+
from .class_validators import root_validator, validator
|
5 |
+
from .config import BaseConfig, ConfigDict, Extra
|
6 |
+
from .decorator import validate_arguments
|
7 |
+
from .env_settings import BaseSettings
|
8 |
+
from .error_wrappers import ValidationError
|
9 |
+
from .errors import *
|
10 |
+
from .fields import Field, PrivateAttr, Required
|
11 |
+
from .main import *
|
12 |
+
from .networks import *
|
13 |
+
from .parse import Protocol
|
14 |
+
from .tools import *
|
15 |
+
from .types import *
|
16 |
+
from .version import VERSION, compiled
|
17 |
+
|
18 |
+
__version__ = VERSION
|
19 |
+
|
20 |
+
# WARNING __all__ from .errors is not included here, it will be removed as an export here in v2
|
21 |
+
# please use "from pydantic.errors import ..." instead
|
22 |
+
__all__ = [
|
23 |
+
# annotated types utils
|
24 |
+
'create_model_from_namedtuple',
|
25 |
+
'create_model_from_typeddict',
|
26 |
+
# dataclasses
|
27 |
+
'dataclasses',
|
28 |
+
# class_validators
|
29 |
+
'root_validator',
|
30 |
+
'validator',
|
31 |
+
# config
|
32 |
+
'BaseConfig',
|
33 |
+
'ConfigDict',
|
34 |
+
'Extra',
|
35 |
+
# decorator
|
36 |
+
'validate_arguments',
|
37 |
+
# env_settings
|
38 |
+
'BaseSettings',
|
39 |
+
# error_wrappers
|
40 |
+
'ValidationError',
|
41 |
+
# fields
|
42 |
+
'Field',
|
43 |
+
'Required',
|
44 |
+
# main
|
45 |
+
'BaseModel',
|
46 |
+
'create_model',
|
47 |
+
'validate_model',
|
48 |
+
# network
|
49 |
+
'AnyUrl',
|
50 |
+
'AnyHttpUrl',
|
51 |
+
'FileUrl',
|
52 |
+
'HttpUrl',
|
53 |
+
'stricturl',
|
54 |
+
'EmailStr',
|
55 |
+
'NameEmail',
|
56 |
+
'IPvAnyAddress',
|
57 |
+
'IPvAnyInterface',
|
58 |
+
'IPvAnyNetwork',
|
59 |
+
'PostgresDsn',
|
60 |
+
'CockroachDsn',
|
61 |
+
'AmqpDsn',
|
62 |
+
'RedisDsn',
|
63 |
+
'MongoDsn',
|
64 |
+
'KafkaDsn',
|
65 |
+
'validate_email',
|
66 |
+
# parse
|
67 |
+
'Protocol',
|
68 |
+
# tools
|
69 |
+
'parse_file_as',
|
70 |
+
'parse_obj_as',
|
71 |
+
'parse_raw_as',
|
72 |
+
'schema_of',
|
73 |
+
'schema_json_of',
|
74 |
+
# types
|
75 |
+
'NoneStr',
|
76 |
+
'NoneBytes',
|
77 |
+
'StrBytes',
|
78 |
+
'NoneStrBytes',
|
79 |
+
'StrictStr',
|
80 |
+
'ConstrainedBytes',
|
81 |
+
'conbytes',
|
82 |
+
'ConstrainedList',
|
83 |
+
'conlist',
|
84 |
+
'ConstrainedSet',
|
85 |
+
'conset',
|
86 |
+
'ConstrainedFrozenSet',
|
87 |
+
'confrozenset',
|
88 |
+
'ConstrainedStr',
|
89 |
+
'constr',
|
90 |
+
'PyObject',
|
91 |
+
'ConstrainedInt',
|
92 |
+
'conint',
|
93 |
+
'PositiveInt',
|
94 |
+
'NegativeInt',
|
95 |
+
'NonNegativeInt',
|
96 |
+
'NonPositiveInt',
|
97 |
+
'ConstrainedFloat',
|
98 |
+
'confloat',
|
99 |
+
'PositiveFloat',
|
100 |
+
'NegativeFloat',
|
101 |
+
'NonNegativeFloat',
|
102 |
+
'NonPositiveFloat',
|
103 |
+
'FiniteFloat',
|
104 |
+
'ConstrainedDecimal',
|
105 |
+
'condecimal',
|
106 |
+
'ConstrainedDate',
|
107 |
+
'condate',
|
108 |
+
'UUID1',
|
109 |
+
'UUID3',
|
110 |
+
'UUID4',
|
111 |
+
'UUID5',
|
112 |
+
'FilePath',
|
113 |
+
'DirectoryPath',
|
114 |
+
'Json',
|
115 |
+
'JsonWrapper',
|
116 |
+
'SecretField',
|
117 |
+
'SecretStr',
|
118 |
+
'SecretBytes',
|
119 |
+
'StrictBool',
|
120 |
+
'StrictBytes',
|
121 |
+
'StrictInt',
|
122 |
+
'StrictFloat',
|
123 |
+
'PaymentCardNumber',
|
124 |
+
'PrivateAttr',
|
125 |
+
'ByteSize',
|
126 |
+
'PastDate',
|
127 |
+
'FutureDate',
|
128 |
+
# version
|
129 |
+
'compiled',
|
130 |
+
'VERSION',
|
131 |
+
]
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.99 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/_hypothesis_plugin.cpython-310.pyc
ADDED
Binary file (10.3 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/annotated_types.cpython-310.pyc
ADDED
Binary file (3.14 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/class_validators.cpython-310.pyc
ADDED
Binary file (13.6 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/color.cpython-310.pyc
ADDED
Binary file (18.1 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/config.cpython-310.pyc
ADDED
Binary file (6.04 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/dataclasses.cpython-310.pyc
ADDED
Binary file (15.1 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/datetime_parse.cpython-310.pyc
ADDED
Binary file (6.63 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/decorator.cpython-310.pyc
ADDED
Binary file (8.72 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/env_settings.cpython-310.pyc
ADDED
Binary file (11.8 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/fields.cpython-310.pyc
ADDED
Binary file (34.7 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/generics.cpython-310.pyc
ADDED
Binary file (11.4 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/main.cpython-310.pyc
ADDED
Binary file (29.6 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/mypy.cpython-310.pyc
ADDED
Binary file (29.2 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/parse.cpython-310.pyc
ADDED
Binary file (1.77 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/schema.cpython-310.pyc
ADDED
Binary file (32.6 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/tools.cpython-310.pyc
ADDED
Binary file (2.76 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/types.cpython-310.pyc
ADDED
Binary file (32.7 kB). View file
|
|
venv/lib/python3.10/site-packages/pydantic/v1/__pycache__/typing.cpython-310.pyc
ADDED
Binary file (14.7 kB). View file
|
|