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,248 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions to parse datetime objects.
|
|
3
|
+
|
|
4
|
+
We're using regular expressions rather than time.strptime because:
|
|
5
|
+
- They provide both validation and parsing.
|
|
6
|
+
- They're more flexible for datetimes.
|
|
7
|
+
- The date/datetime/time constructors produce friendlier error messages.
|
|
8
|
+
|
|
9
|
+
Stolen from https://raw.githubusercontent.com/django/django/main/django/utils/dateparse.py at
|
|
10
|
+
9718fa2e8abe430c3526a9278dd976443d4ae3c6
|
|
11
|
+
|
|
12
|
+
Changed to:
|
|
13
|
+
* use standard python datetime types not django.utils.timezone
|
|
14
|
+
* raise ValueError when regex doesn't match rather than returning None
|
|
15
|
+
* support parsing unix timestamps for dates and datetimes
|
|
16
|
+
"""
|
|
17
|
+
import re
|
|
18
|
+
from datetime import date, datetime, time, timedelta, timezone
|
|
19
|
+
from typing import Dict, Optional, Type, Union
|
|
20
|
+
|
|
21
|
+
from pboot_validator.v1 import errors
|
|
22
|
+
|
|
23
|
+
date_expr = r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
|
|
24
|
+
time_expr = (
|
|
25
|
+
r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
|
|
26
|
+
r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
|
|
27
|
+
r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$'
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
date_re = re.compile(f'{date_expr}$')
|
|
31
|
+
time_re = re.compile(time_expr)
|
|
32
|
+
datetime_re = re.compile(f'{date_expr}[T ]{time_expr}')
|
|
33
|
+
|
|
34
|
+
standard_duration_re = re.compile(
|
|
35
|
+
r'^'
|
|
36
|
+
r'(?:(?P<days>-?\d+) (days?, )?)?'
|
|
37
|
+
r'((?:(?P<hours>-?\d+):)(?=\d+:\d+))?'
|
|
38
|
+
r'(?:(?P<minutes>-?\d+):)?'
|
|
39
|
+
r'(?P<seconds>-?\d+)'
|
|
40
|
+
r'(?:\.(?P<microseconds>\d{1,6})\d{0,6})?'
|
|
41
|
+
r'$'
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
# Support the sections of ISO 8601 date representation that are accepted by timedelta
|
|
45
|
+
iso8601_duration_re = re.compile(
|
|
46
|
+
r'^(?P<sign>[-+]?)'
|
|
47
|
+
r'P'
|
|
48
|
+
r'(?:(?P<days>\d+(\.\d+)?)D)?'
|
|
49
|
+
r'(?:T'
|
|
50
|
+
r'(?:(?P<hours>\d+(\.\d+)?)H)?'
|
|
51
|
+
r'(?:(?P<minutes>\d+(\.\d+)?)M)?'
|
|
52
|
+
r'(?:(?P<seconds>\d+(\.\d+)?)S)?'
|
|
53
|
+
r')?'
|
|
54
|
+
r'$'
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
EPOCH = datetime(1970, 1, 1)
|
|
58
|
+
# if greater than this, the number is in ms, if less than or equal it's in seconds
|
|
59
|
+
# (in seconds this is 11th October 2603, in ms it's 20th August 1970)
|
|
60
|
+
MS_WATERSHED = int(2e10)
|
|
61
|
+
# slightly more than datetime.max in ns - (datetime.max - EPOCH).total_seconds() * 1e9
|
|
62
|
+
MAX_NUMBER = int(3e20)
|
|
63
|
+
StrBytesIntFloat = Union[str, bytes, int, float]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[None, int, float]:
|
|
67
|
+
if isinstance(value, (int, float)):
|
|
68
|
+
return value
|
|
69
|
+
try:
|
|
70
|
+
return float(value)
|
|
71
|
+
except ValueError:
|
|
72
|
+
return None
|
|
73
|
+
except TypeError:
|
|
74
|
+
raise TypeError(f'invalid type; expected {native_expected_type}, string, bytes, int or float')
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def from_unix_seconds(seconds: Union[int, float]) -> datetime:
|
|
78
|
+
if seconds > MAX_NUMBER:
|
|
79
|
+
return datetime.max
|
|
80
|
+
elif seconds < -MAX_NUMBER:
|
|
81
|
+
return datetime.min
|
|
82
|
+
|
|
83
|
+
while abs(seconds) > MS_WATERSHED:
|
|
84
|
+
seconds /= 1000
|
|
85
|
+
dt = EPOCH + timedelta(seconds=seconds)
|
|
86
|
+
return dt.replace(tzinfo=timezone.utc)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _parse_timezone(value: Optional[str], error: Type[Exception]) -> Union[None, int, timezone]:
|
|
90
|
+
if value == 'Z':
|
|
91
|
+
return timezone.utc
|
|
92
|
+
elif value is not None:
|
|
93
|
+
offset_mins = int(value[-2:]) if len(value) > 3 else 0
|
|
94
|
+
offset = 60 * int(value[1:3]) + offset_mins
|
|
95
|
+
if value[0] == '-':
|
|
96
|
+
offset = -offset
|
|
97
|
+
try:
|
|
98
|
+
return timezone(timedelta(minutes=offset))
|
|
99
|
+
except ValueError:
|
|
100
|
+
raise error()
|
|
101
|
+
else:
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def parse_date(value: Union[date, StrBytesIntFloat]) -> date:
|
|
106
|
+
"""
|
|
107
|
+
Parse a date/int/float/string and return a datetime.date.
|
|
108
|
+
|
|
109
|
+
Raise ValueError if the input is well formatted but not a valid date.
|
|
110
|
+
Raise ValueError if the input isn't well formatted.
|
|
111
|
+
"""
|
|
112
|
+
if isinstance(value, date):
|
|
113
|
+
if isinstance(value, datetime):
|
|
114
|
+
return value.date()
|
|
115
|
+
else:
|
|
116
|
+
return value
|
|
117
|
+
|
|
118
|
+
number = get_numeric(value, 'date')
|
|
119
|
+
if number is not None:
|
|
120
|
+
return from_unix_seconds(number).date()
|
|
121
|
+
|
|
122
|
+
if isinstance(value, bytes):
|
|
123
|
+
value = value.decode()
|
|
124
|
+
|
|
125
|
+
match = date_re.match(value) # type: ignore
|
|
126
|
+
if match is None:
|
|
127
|
+
raise errors.DateError()
|
|
128
|
+
|
|
129
|
+
kw = {k: int(v) for k, v in match.groupdict().items()}
|
|
130
|
+
|
|
131
|
+
try:
|
|
132
|
+
return date(**kw)
|
|
133
|
+
except ValueError:
|
|
134
|
+
raise errors.DateError()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def parse_time(value: Union[time, StrBytesIntFloat]) -> time:
|
|
138
|
+
"""
|
|
139
|
+
Parse a time/string and return a datetime.time.
|
|
140
|
+
|
|
141
|
+
Raise ValueError if the input is well formatted but not a valid time.
|
|
142
|
+
Raise ValueError if the input isn't well formatted, in particular if it contains an offset.
|
|
143
|
+
"""
|
|
144
|
+
if isinstance(value, time):
|
|
145
|
+
return value
|
|
146
|
+
|
|
147
|
+
number = get_numeric(value, 'time')
|
|
148
|
+
if number is not None:
|
|
149
|
+
if number >= 86400:
|
|
150
|
+
# doesn't make sense since the time time loop back around to 0
|
|
151
|
+
raise errors.TimeError()
|
|
152
|
+
return (datetime.min + timedelta(seconds=number)).time()
|
|
153
|
+
|
|
154
|
+
if isinstance(value, bytes):
|
|
155
|
+
value = value.decode()
|
|
156
|
+
|
|
157
|
+
match = time_re.match(value) # type: ignore
|
|
158
|
+
if match is None:
|
|
159
|
+
raise errors.TimeError()
|
|
160
|
+
|
|
161
|
+
kw = match.groupdict()
|
|
162
|
+
if kw['microsecond']:
|
|
163
|
+
kw['microsecond'] = kw['microsecond'].ljust(6, '0')
|
|
164
|
+
|
|
165
|
+
tzinfo = _parse_timezone(kw.pop('tzinfo'), errors.TimeError)
|
|
166
|
+
kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None}
|
|
167
|
+
kw_['tzinfo'] = tzinfo
|
|
168
|
+
|
|
169
|
+
try:
|
|
170
|
+
return time(**kw_) # type: ignore
|
|
171
|
+
except ValueError:
|
|
172
|
+
raise errors.TimeError()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime:
|
|
176
|
+
"""
|
|
177
|
+
Parse a datetime/int/float/string and return a datetime.datetime.
|
|
178
|
+
|
|
179
|
+
This function supports time zone offsets. When the input contains one,
|
|
180
|
+
the output uses a timezone with a fixed offset from UTC.
|
|
181
|
+
|
|
182
|
+
Raise ValueError if the input is well formatted but not a valid datetime.
|
|
183
|
+
Raise ValueError if the input isn't well formatted.
|
|
184
|
+
"""
|
|
185
|
+
if isinstance(value, datetime):
|
|
186
|
+
return value
|
|
187
|
+
|
|
188
|
+
number = get_numeric(value, 'datetime')
|
|
189
|
+
if number is not None:
|
|
190
|
+
return from_unix_seconds(number)
|
|
191
|
+
|
|
192
|
+
if isinstance(value, bytes):
|
|
193
|
+
value = value.decode()
|
|
194
|
+
|
|
195
|
+
match = datetime_re.match(value) # type: ignore
|
|
196
|
+
if match is None:
|
|
197
|
+
raise errors.DateTimeError()
|
|
198
|
+
|
|
199
|
+
kw = match.groupdict()
|
|
200
|
+
if kw['microsecond']:
|
|
201
|
+
kw['microsecond'] = kw['microsecond'].ljust(6, '0')
|
|
202
|
+
|
|
203
|
+
tzinfo = _parse_timezone(kw.pop('tzinfo'), errors.DateTimeError)
|
|
204
|
+
kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None}
|
|
205
|
+
kw_['tzinfo'] = tzinfo
|
|
206
|
+
|
|
207
|
+
try:
|
|
208
|
+
return datetime(**kw_) # type: ignore
|
|
209
|
+
except ValueError:
|
|
210
|
+
raise errors.DateTimeError()
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def parse_duration(value: StrBytesIntFloat) -> timedelta:
|
|
214
|
+
"""
|
|
215
|
+
Parse a duration int/float/string and return a datetime.timedelta.
|
|
216
|
+
|
|
217
|
+
The preferred format for durations in Django is '%d %H:%M:%S.%f'.
|
|
218
|
+
|
|
219
|
+
Also supports ISO 8601 representation.
|
|
220
|
+
"""
|
|
221
|
+
if isinstance(value, timedelta):
|
|
222
|
+
return value
|
|
223
|
+
|
|
224
|
+
if isinstance(value, (int, float)):
|
|
225
|
+
# below code requires a string
|
|
226
|
+
value = f'{value:f}'
|
|
227
|
+
elif isinstance(value, bytes):
|
|
228
|
+
value = value.decode()
|
|
229
|
+
|
|
230
|
+
try:
|
|
231
|
+
match = standard_duration_re.match(value) or iso8601_duration_re.match(value)
|
|
232
|
+
except TypeError:
|
|
233
|
+
raise TypeError('invalid type; expected timedelta, string, bytes, int or float')
|
|
234
|
+
|
|
235
|
+
if not match:
|
|
236
|
+
raise errors.DurationError()
|
|
237
|
+
|
|
238
|
+
kw = match.groupdict()
|
|
239
|
+
sign = -1 if kw.pop('sign', '+') == '-' else 1
|
|
240
|
+
if kw.get('microseconds'):
|
|
241
|
+
kw['microseconds'] = kw['microseconds'].ljust(6, '0')
|
|
242
|
+
|
|
243
|
+
if kw.get('seconds') and kw.get('microseconds') and kw['seconds'].startswith('-'):
|
|
244
|
+
kw['microseconds'] = '-' + kw['microseconds']
|
|
245
|
+
|
|
246
|
+
kw_ = {k: float(v) for k, v in kw.items() if v is not None}
|
|
247
|
+
|
|
248
|
+
return sign * timedelta(**kw_)
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
from functools import wraps
|
|
2
|
+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, TypeVar, Union, overload
|
|
3
|
+
|
|
4
|
+
from pboot_validator.v1 import validator
|
|
5
|
+
from pboot_validator.v1.config import Extra
|
|
6
|
+
from pboot_validator.v1.errors import ConfigError
|
|
7
|
+
from pboot_validator.v1.main import BaseModel, create_model
|
|
8
|
+
from pboot_validator.v1.typing import get_all_type_hints
|
|
9
|
+
from pboot_validator.v1.utils import to_camel
|
|
10
|
+
|
|
11
|
+
__all__ = ('validate_arguments',)
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from pboot_validator.v1.typing import AnyCallable
|
|
15
|
+
|
|
16
|
+
AnyCallableT = TypeVar('AnyCallableT', bound=AnyCallable)
|
|
17
|
+
ConfigType = Union[None, Type[Any], Dict[str, Any]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@overload
|
|
21
|
+
def validate_arguments(func: None = None, *, config: 'ConfigType' = None) -> Callable[['AnyCallableT'], 'AnyCallableT']:
|
|
22
|
+
...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@overload
|
|
26
|
+
def validate_arguments(func: 'AnyCallableT') -> 'AnyCallableT':
|
|
27
|
+
...
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def validate_arguments(func: Optional['AnyCallableT'] = None, *, config: 'ConfigType' = None) -> Any:
|
|
31
|
+
"""
|
|
32
|
+
Decorator to validate the arguments passed to a function.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def validate(_func: 'AnyCallable') -> 'AnyCallable':
|
|
36
|
+
vd = ValidatedFunction(_func, config)
|
|
37
|
+
|
|
38
|
+
@wraps(_func)
|
|
39
|
+
def wrapper_function(*args: Any, **kwargs: Any) -> Any:
|
|
40
|
+
return vd.call(*args, **kwargs)
|
|
41
|
+
|
|
42
|
+
wrapper_function.vd = vd # type: ignore
|
|
43
|
+
wrapper_function.validate = vd.init_model_instance # type: ignore
|
|
44
|
+
wrapper_function.raw_function = vd.raw_function # type: ignore
|
|
45
|
+
wrapper_function.model = vd.model # type: ignore
|
|
46
|
+
return wrapper_function
|
|
47
|
+
|
|
48
|
+
if func:
|
|
49
|
+
return validate(func)
|
|
50
|
+
else:
|
|
51
|
+
return validate
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
ALT_V_ARGS = 'v__args'
|
|
55
|
+
ALT_V_KWARGS = 'v__kwargs'
|
|
56
|
+
V_POSITIONAL_ONLY_NAME = 'v__positional_only'
|
|
57
|
+
V_DUPLICATE_KWARGS = 'v__duplicate_kwargs'
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ValidatedFunction:
|
|
61
|
+
def __init__(self, function: 'AnyCallableT', config: 'ConfigType'): # noqa C901
|
|
62
|
+
from inspect import Parameter, signature
|
|
63
|
+
|
|
64
|
+
parameters: Mapping[str, Parameter] = signature(function).parameters
|
|
65
|
+
|
|
66
|
+
if parameters.keys() & {ALT_V_ARGS, ALT_V_KWARGS, V_POSITIONAL_ONLY_NAME, V_DUPLICATE_KWARGS}:
|
|
67
|
+
raise ConfigError(
|
|
68
|
+
f'"{ALT_V_ARGS}", "{ALT_V_KWARGS}", "{V_POSITIONAL_ONLY_NAME}" and "{V_DUPLICATE_KWARGS}" '
|
|
69
|
+
f'are not permitted as argument names when using the "{validate_arguments.__name__}" decorator'
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
self.raw_function = function
|
|
73
|
+
self.arg_mapping: Dict[int, str] = {}
|
|
74
|
+
self.positional_only_args = set()
|
|
75
|
+
self.v_args_name = 'args'
|
|
76
|
+
self.v_kwargs_name = 'kwargs'
|
|
77
|
+
|
|
78
|
+
type_hints = get_all_type_hints(function)
|
|
79
|
+
takes_args = False
|
|
80
|
+
takes_kwargs = False
|
|
81
|
+
fields: Dict[str, Tuple[Any, Any]] = {}
|
|
82
|
+
for i, (name, p) in enumerate(parameters.items()):
|
|
83
|
+
if p.annotation is p.empty:
|
|
84
|
+
annotation = Any
|
|
85
|
+
else:
|
|
86
|
+
annotation = type_hints[name]
|
|
87
|
+
|
|
88
|
+
default = ... if p.default is p.empty else p.default
|
|
89
|
+
if p.kind == Parameter.POSITIONAL_ONLY:
|
|
90
|
+
self.arg_mapping[i] = name
|
|
91
|
+
fields[name] = annotation, default
|
|
92
|
+
fields[V_POSITIONAL_ONLY_NAME] = List[str], None
|
|
93
|
+
self.positional_only_args.add(name)
|
|
94
|
+
elif p.kind == Parameter.POSITIONAL_OR_KEYWORD:
|
|
95
|
+
self.arg_mapping[i] = name
|
|
96
|
+
fields[name] = annotation, default
|
|
97
|
+
fields[V_DUPLICATE_KWARGS] = List[str], None
|
|
98
|
+
elif p.kind == Parameter.KEYWORD_ONLY:
|
|
99
|
+
fields[name] = annotation, default
|
|
100
|
+
elif p.kind == Parameter.VAR_POSITIONAL:
|
|
101
|
+
self.v_args_name = name
|
|
102
|
+
fields[name] = Tuple[annotation, ...], None
|
|
103
|
+
takes_args = True
|
|
104
|
+
else:
|
|
105
|
+
assert p.kind == Parameter.VAR_KEYWORD, p.kind
|
|
106
|
+
self.v_kwargs_name = name
|
|
107
|
+
fields[name] = Dict[str, annotation], None # type: ignore
|
|
108
|
+
takes_kwargs = True
|
|
109
|
+
|
|
110
|
+
# these checks avoid a clash between "args" and a field with that name
|
|
111
|
+
if not takes_args and self.v_args_name in fields:
|
|
112
|
+
self.v_args_name = ALT_V_ARGS
|
|
113
|
+
|
|
114
|
+
# same with "kwargs"
|
|
115
|
+
if not takes_kwargs and self.v_kwargs_name in fields:
|
|
116
|
+
self.v_kwargs_name = ALT_V_KWARGS
|
|
117
|
+
|
|
118
|
+
if not takes_args:
|
|
119
|
+
# we add the field so validation below can raise the correct exception
|
|
120
|
+
fields[self.v_args_name] = List[Any], None
|
|
121
|
+
|
|
122
|
+
if not takes_kwargs:
|
|
123
|
+
# same with kwargs
|
|
124
|
+
fields[self.v_kwargs_name] = Dict[Any, Any], None
|
|
125
|
+
|
|
126
|
+
self.create_model(fields, takes_args, takes_kwargs, config)
|
|
127
|
+
|
|
128
|
+
def init_model_instance(self, *args: Any, **kwargs: Any) -> BaseModel:
|
|
129
|
+
values = self.build_values(args, kwargs)
|
|
130
|
+
return self.model(**values)
|
|
131
|
+
|
|
132
|
+
def call(self, *args: Any, **kwargs: Any) -> Any:
|
|
133
|
+
m = self.init_model_instance(*args, **kwargs)
|
|
134
|
+
return self.execute(m)
|
|
135
|
+
|
|
136
|
+
def build_values(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
|
137
|
+
values: Dict[str, Any] = {}
|
|
138
|
+
if args:
|
|
139
|
+
arg_iter = enumerate(args)
|
|
140
|
+
while True:
|
|
141
|
+
try:
|
|
142
|
+
i, a = next(arg_iter)
|
|
143
|
+
except StopIteration:
|
|
144
|
+
break
|
|
145
|
+
arg_name = self.arg_mapping.get(i)
|
|
146
|
+
if arg_name is not None:
|
|
147
|
+
values[arg_name] = a
|
|
148
|
+
else:
|
|
149
|
+
values[self.v_args_name] = [a] + [a for _, a in arg_iter]
|
|
150
|
+
break
|
|
151
|
+
|
|
152
|
+
var_kwargs: Dict[str, Any] = {}
|
|
153
|
+
wrong_positional_args = []
|
|
154
|
+
duplicate_kwargs = []
|
|
155
|
+
fields_alias = [
|
|
156
|
+
field.alias
|
|
157
|
+
for name, field in self.model.__fields__.items()
|
|
158
|
+
if name not in (self.v_args_name, self.v_kwargs_name)
|
|
159
|
+
]
|
|
160
|
+
non_var_fields = set(self.model.__fields__) - {self.v_args_name, self.v_kwargs_name}
|
|
161
|
+
for k, v in kwargs.items():
|
|
162
|
+
if k in non_var_fields or k in fields_alias:
|
|
163
|
+
if k in self.positional_only_args:
|
|
164
|
+
wrong_positional_args.append(k)
|
|
165
|
+
if k in values:
|
|
166
|
+
duplicate_kwargs.append(k)
|
|
167
|
+
values[k] = v
|
|
168
|
+
else:
|
|
169
|
+
var_kwargs[k] = v
|
|
170
|
+
|
|
171
|
+
if var_kwargs:
|
|
172
|
+
values[self.v_kwargs_name] = var_kwargs
|
|
173
|
+
if wrong_positional_args:
|
|
174
|
+
values[V_POSITIONAL_ONLY_NAME] = wrong_positional_args
|
|
175
|
+
if duplicate_kwargs:
|
|
176
|
+
values[V_DUPLICATE_KWARGS] = duplicate_kwargs
|
|
177
|
+
return values
|
|
178
|
+
|
|
179
|
+
def execute(self, m: BaseModel) -> Any:
|
|
180
|
+
d = {k: v for k, v in m._iter() if k in m.__fields_set__ or m.__fields__[k].default_factory}
|
|
181
|
+
var_kwargs = d.pop(self.v_kwargs_name, {})
|
|
182
|
+
|
|
183
|
+
if self.v_args_name in d:
|
|
184
|
+
args_: List[Any] = []
|
|
185
|
+
in_kwargs = False
|
|
186
|
+
kwargs = {}
|
|
187
|
+
for name, value in d.items():
|
|
188
|
+
if in_kwargs:
|
|
189
|
+
kwargs[name] = value
|
|
190
|
+
elif name == self.v_args_name:
|
|
191
|
+
args_ += value
|
|
192
|
+
in_kwargs = True
|
|
193
|
+
else:
|
|
194
|
+
args_.append(value)
|
|
195
|
+
return self.raw_function(*args_, **kwargs, **var_kwargs)
|
|
196
|
+
elif self.positional_only_args:
|
|
197
|
+
args_ = []
|
|
198
|
+
kwargs = {}
|
|
199
|
+
for name, value in d.items():
|
|
200
|
+
if name in self.positional_only_args:
|
|
201
|
+
args_.append(value)
|
|
202
|
+
else:
|
|
203
|
+
kwargs[name] = value
|
|
204
|
+
return self.raw_function(*args_, **kwargs, **var_kwargs)
|
|
205
|
+
else:
|
|
206
|
+
return self.raw_function(**d, **var_kwargs)
|
|
207
|
+
|
|
208
|
+
def create_model(self, fields: Dict[str, Any], takes_args: bool, takes_kwargs: bool, config: 'ConfigType') -> None:
|
|
209
|
+
pos_args = len(self.arg_mapping)
|
|
210
|
+
|
|
211
|
+
class CustomConfig:
|
|
212
|
+
pass
|
|
213
|
+
|
|
214
|
+
if not TYPE_CHECKING: # pragma: no branch
|
|
215
|
+
if isinstance(config, dict):
|
|
216
|
+
CustomConfig = type('Config', (), config) # noqa: F811
|
|
217
|
+
elif config is not None:
|
|
218
|
+
CustomConfig = config # noqa: F811
|
|
219
|
+
|
|
220
|
+
if hasattr(CustomConfig, 'fields') or hasattr(CustomConfig, 'alias_generator'):
|
|
221
|
+
raise ConfigError(
|
|
222
|
+
'Setting the "fields" and "alias_generator" property on custom Config for '
|
|
223
|
+
'@validate_arguments is not yet supported, please remove.'
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
class DecoratorBaseModel(BaseModel):
|
|
227
|
+
@validator(self.v_args_name, check_fields=False, allow_reuse=True)
|
|
228
|
+
def check_args(cls, v: Optional[List[Any]]) -> Optional[List[Any]]:
|
|
229
|
+
if takes_args or v is None:
|
|
230
|
+
return v
|
|
231
|
+
|
|
232
|
+
raise TypeError(f'{pos_args} positional arguments expected but {pos_args + len(v)} given')
|
|
233
|
+
|
|
234
|
+
@validator(self.v_kwargs_name, check_fields=False, allow_reuse=True)
|
|
235
|
+
def check_kwargs(cls, v: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
|
236
|
+
if takes_kwargs or v is None:
|
|
237
|
+
return v
|
|
238
|
+
|
|
239
|
+
plural = '' if len(v) == 1 else 's'
|
|
240
|
+
keys = ', '.join(map(repr, v.keys()))
|
|
241
|
+
raise TypeError(f'unexpected keyword argument{plural}: {keys}')
|
|
242
|
+
|
|
243
|
+
@validator(V_POSITIONAL_ONLY_NAME, check_fields=False, allow_reuse=True)
|
|
244
|
+
def check_positional_only(cls, v: Optional[List[str]]) -> None:
|
|
245
|
+
if v is None:
|
|
246
|
+
return
|
|
247
|
+
|
|
248
|
+
plural = '' if len(v) == 1 else 's'
|
|
249
|
+
keys = ', '.join(map(repr, v))
|
|
250
|
+
raise TypeError(f'positional-only argument{plural} passed as keyword argument{plural}: {keys}')
|
|
251
|
+
|
|
252
|
+
@validator(V_DUPLICATE_KWARGS, check_fields=False, allow_reuse=True)
|
|
253
|
+
def check_duplicate_kwargs(cls, v: Optional[List[str]]) -> None:
|
|
254
|
+
if v is None:
|
|
255
|
+
return
|
|
256
|
+
|
|
257
|
+
plural = '' if len(v) == 1 else 's'
|
|
258
|
+
keys = ', '.join(map(repr, v))
|
|
259
|
+
raise TypeError(f'multiple values for argument{plural}: {keys}')
|
|
260
|
+
|
|
261
|
+
class Config(CustomConfig):
|
|
262
|
+
extra = getattr(CustomConfig, 'extra', Extra.forbid)
|
|
263
|
+
|
|
264
|
+
self.model = create_model(to_camel(self.raw_function.__name__), __base__=DecoratorBaseModel, **fields)
|