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.
Files changed (112) hide show
  1. pboot_validator/__init__.py +461 -0
  2. pboot_validator/_internal/__init__.py +0 -0
  3. pboot_validator/_internal/_config.py +408 -0
  4. pboot_validator/_internal/_contextlib.py +84 -0
  5. pboot_validator/_internal/_core_metadata.py +97 -0
  6. pboot_validator/_internal/_core_utils.py +156 -0
  7. pboot_validator/_internal/_dataclasses.py +327 -0
  8. pboot_validator/_internal/_decorators.py +906 -0
  9. pboot_validator/_internal/_decorators_v1.py +174 -0
  10. pboot_validator/_internal/_discriminated_union.py +510 -0
  11. pboot_validator/_internal/_docs_extraction.py +128 -0
  12. pboot_validator/_internal/_fields.py +910 -0
  13. pboot_validator/_internal/_forward_ref.py +23 -0
  14. pboot_validator/_internal/_generate_schema.py +3053 -0
  15. pboot_validator/_internal/_generics.py +572 -0
  16. pboot_validator/_internal/_git.py +27 -0
  17. pboot_validator/_internal/_import_utils.py +20 -0
  18. pboot_validator/_internal/_known_annotated_metadata.py +412 -0
  19. pboot_validator/_internal/_mock_val_ser.py +241 -0
  20. pboot_validator/_internal/_model_construction.py +833 -0
  21. pboot_validator/_internal/_namespace_utils.py +300 -0
  22. pboot_validator/_internal/_repr.py +129 -0
  23. pboot_validator/_internal/_schema_gather.py +49 -0
  24. pboot_validator/_internal/_schema_generation_shared.py +126 -0
  25. pboot_validator/_internal/_serializers.py +59 -0
  26. pboot_validator/_internal/_signature.py +193 -0
  27. pboot_validator/_internal/_type_refs.py +128 -0
  28. pboot_validator/_internal/_typing_extra.py +506 -0
  29. pboot_validator/_internal/_utils.py +433 -0
  30. pboot_validator/_internal/_validate_call.py +141 -0
  31. pboot_validator/_internal/_validators.py +541 -0
  32. pboot_validator/_migration.py +317 -0
  33. pboot_validator/alias_generators.py +62 -0
  34. pboot_validator/aliases.py +136 -0
  35. pboot_validator/annotated_handlers.py +123 -0
  36. pboot_validator/class_validators.py +5 -0
  37. pboot_validator/color.py +605 -0
  38. pboot_validator/config.py +1295 -0
  39. pboot_validator/dataclasses.py +385 -0
  40. pboot_validator/datetime_parse.py +5 -0
  41. pboot_validator/decorator.py +5 -0
  42. pboot_validator/deprecated/__init__.py +0 -0
  43. pboot_validator/deprecated/class_validators.py +257 -0
  44. pboot_validator/deprecated/config.py +72 -0
  45. pboot_validator/deprecated/copy_internals.py +224 -0
  46. pboot_validator/deprecated/decorator.py +286 -0
  47. pboot_validator/deprecated/json.py +142 -0
  48. pboot_validator/deprecated/parse.py +81 -0
  49. pboot_validator/deprecated/tools.py +104 -0
  50. pboot_validator/env_settings.py +5 -0
  51. pboot_validator/error_wrappers.py +5 -0
  52. pboot_validator/errors.py +185 -0
  53. pboot_validator/experimental/__init__.py +1 -0
  54. pboot_validator/experimental/arguments_schema.py +44 -0
  55. pboot_validator/experimental/missing_sentinel.py +29 -0
  56. pboot_validator/experimental/pipeline.py +684 -0
  57. pboot_validator/fields.py +2065 -0
  58. pboot_validator/functional_serializers.py +461 -0
  59. pboot_validator/functional_validators.py +920 -0
  60. pboot_validator/generics.py +5 -0
  61. pboot_validator/json.py +5 -0
  62. pboot_validator/json_schema.py +3283 -0
  63. pboot_validator/main.py +1947 -0
  64. pboot_validator/mypy.py +1469 -0
  65. pboot_validator/networks.py +1417 -0
  66. pboot_validator/parse.py +5 -0
  67. pboot_validator/plugin/__init__.py +190 -0
  68. pboot_validator/plugin/_loader.py +56 -0
  69. pboot_validator/plugin/_schema_validator.py +152 -0
  70. pboot_validator/py.typed +0 -0
  71. pboot_validator/root_model.py +189 -0
  72. pboot_validator/schema.py +5 -0
  73. pboot_validator/tools.py +5 -0
  74. pboot_validator/type_adapter.py +780 -0
  75. pboot_validator/types.py +3405 -0
  76. pboot_validator/typing.py +5 -0
  77. pboot_validator/utils.py +5 -0
  78. pboot_validator/v1/__init__.py +131 -0
  79. pboot_validator/v1/_hypothesis_plugin.py +391 -0
  80. pboot_validator/v1/annotated_types.py +72 -0
  81. pboot_validator/v1/class_validators.py +361 -0
  82. pboot_validator/v1/color.py +494 -0
  83. pboot_validator/v1/config.py +191 -0
  84. pboot_validator/v1/dataclasses.py +503 -0
  85. pboot_validator/v1/datetime_parse.py +248 -0
  86. pboot_validator/v1/decorator.py +264 -0
  87. pboot_validator/v1/env_settings.py +350 -0
  88. pboot_validator/v1/error_wrappers.py +161 -0
  89. pboot_validator/v1/errors.py +646 -0
  90. pboot_validator/v1/fields.py +1253 -0
  91. pboot_validator/v1/generics.py +400 -0
  92. pboot_validator/v1/json.py +112 -0
  93. pboot_validator/v1/main.py +1130 -0
  94. pboot_validator/v1/mypy.py +950 -0
  95. pboot_validator/v1/networks.py +747 -0
  96. pboot_validator/v1/parse.py +66 -0
  97. pboot_validator/v1/py.typed +0 -0
  98. pboot_validator/v1/schema.py +1163 -0
  99. pboot_validator/v1/tools.py +92 -0
  100. pboot_validator/v1/types.py +1213 -0
  101. pboot_validator/v1/typing.py +627 -0
  102. pboot_validator/v1/utils.py +807 -0
  103. pboot_validator/v1/validators.py +768 -0
  104. pboot_validator/v1/version.py +38 -0
  105. pboot_validator/validate_call_decorator.py +121 -0
  106. pboot_validator/validators.py +5 -0
  107. pboot_validator/version.py +113 -0
  108. pboot_validator/warnings.py +130 -0
  109. pboot_validator-1.0.0.dist-info/METADATA +93 -0
  110. pboot_validator-1.0.0.dist-info/RECORD +112 -0
  111. pboot_validator-1.0.0.dist-info/WHEEL +4 -0
  112. pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,361 @@
1
+ import warnings
2
+ from collections import ChainMap
3
+ from functools import partial, partialmethod, wraps
4
+ from itertools import chain
5
+ from types import FunctionType
6
+ from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, Union, overload
7
+
8
+ from pboot_validator.v1.errors import ConfigError
9
+ from pboot_validator.v1.typing import AnyCallable
10
+ from pboot_validator.v1.utils import ROOT_KEY, in_ipython
11
+
12
+ if TYPE_CHECKING:
13
+ from pboot_validator.v1.typing import AnyClassMethod
14
+
15
+
16
+ class Validator:
17
+ __slots__ = 'func', 'pre', 'each_item', 'always', 'check_fields', 'skip_on_failure'
18
+
19
+ def __init__(
20
+ self,
21
+ func: AnyCallable,
22
+ pre: bool = False,
23
+ each_item: bool = False,
24
+ always: bool = False,
25
+ check_fields: bool = False,
26
+ skip_on_failure: bool = False,
27
+ ):
28
+ self.func = func
29
+ self.pre = pre
30
+ self.each_item = each_item
31
+ self.always = always
32
+ self.check_fields = check_fields
33
+ self.skip_on_failure = skip_on_failure
34
+
35
+
36
+ if TYPE_CHECKING:
37
+ from inspect import Signature
38
+
39
+ from pboot_validator.v1.config import BaseConfig
40
+ from pboot_validator.v1.fields import ModelField
41
+ from pboot_validator.v1.types import ModelOrDc
42
+
43
+ ValidatorCallable = Callable[[Optional[ModelOrDc], Any, Dict[str, Any], ModelField, Type[BaseConfig]], Any]
44
+ ValidatorsList = List[ValidatorCallable]
45
+ ValidatorListDict = Dict[str, List[Validator]]
46
+
47
+ _FUNCS: Set[str] = set()
48
+ VALIDATOR_CONFIG_KEY = '__validator_config__'
49
+ ROOT_VALIDATOR_CONFIG_KEY = '__root_validator_config__'
50
+
51
+
52
+ def validator(
53
+ *fields: str,
54
+ pre: bool = False,
55
+ each_item: bool = False,
56
+ always: bool = False,
57
+ check_fields: bool = True,
58
+ whole: Optional[bool] = None,
59
+ allow_reuse: bool = False,
60
+ ) -> Callable[[AnyCallable], 'AnyClassMethod']:
61
+ """
62
+ Decorate methods on the class indicating that they should be used to validate fields
63
+ :param fields: which field(s) the method should be called on
64
+ :param pre: whether or not this validator should be called before the standard validators (else after)
65
+ :param each_item: for complex objects (sets, lists etc.) whether to validate individual elements rather than the
66
+ whole object
67
+ :param always: whether this method and other validators should be called even if the value is missing
68
+ :param check_fields: whether to check that the fields actually exist on the model
69
+ :param allow_reuse: whether to track and raise an error if another validator refers to the decorated function
70
+ """
71
+ if not fields:
72
+ raise ConfigError('validator with no fields specified')
73
+ elif isinstance(fields[0], FunctionType):
74
+ raise ConfigError(
75
+ "validators should be used with fields and keyword arguments, not bare. " # noqa: Q000
76
+ "E.g. usage should be `@validator('<field_name>', ...)`"
77
+ )
78
+ elif not all(isinstance(field, str) for field in fields):
79
+ raise ConfigError(
80
+ "validator fields should be passed as separate string args. " # noqa: Q000
81
+ "E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`"
82
+ )
83
+
84
+ if whole is not None:
85
+ warnings.warn(
86
+ 'The "whole" keyword argument is deprecated, use "each_item" (inverse meaning, default False) instead',
87
+ DeprecationWarning,
88
+ )
89
+ assert each_item is False, '"each_item" and "whole" conflict, remove "whole"'
90
+ each_item = not whole
91
+
92
+ def dec(f: AnyCallable) -> 'AnyClassMethod':
93
+ f_cls = _prepare_validator(f, allow_reuse)
94
+ setattr(
95
+ f_cls,
96
+ VALIDATOR_CONFIG_KEY,
97
+ (
98
+ fields,
99
+ Validator(func=f_cls.__func__, pre=pre, each_item=each_item, always=always, check_fields=check_fields),
100
+ ),
101
+ )
102
+ return f_cls
103
+
104
+ return dec
105
+
106
+
107
+ @overload
108
+ def root_validator(_func: AnyCallable) -> 'AnyClassMethod':
109
+ ...
110
+
111
+
112
+ @overload
113
+ def root_validator(
114
+ *, pre: bool = False, allow_reuse: bool = False, skip_on_failure: bool = False
115
+ ) -> Callable[[AnyCallable], 'AnyClassMethod']:
116
+ ...
117
+
118
+
119
+ def root_validator(
120
+ _func: Optional[AnyCallable] = None, *, pre: bool = False, allow_reuse: bool = False, skip_on_failure: bool = False
121
+ ) -> Union['AnyClassMethod', Callable[[AnyCallable], 'AnyClassMethod']]:
122
+ """
123
+ Decorate methods on a model indicating that they should be used to validate (and perhaps modify) data either
124
+ before or after standard model parsing/validation is performed.
125
+ """
126
+ if _func:
127
+ f_cls = _prepare_validator(_func, allow_reuse)
128
+ setattr(
129
+ f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=f_cls.__func__, pre=pre, skip_on_failure=skip_on_failure)
130
+ )
131
+ return f_cls
132
+
133
+ def dec(f: AnyCallable) -> 'AnyClassMethod':
134
+ f_cls = _prepare_validator(f, allow_reuse)
135
+ setattr(
136
+ f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=f_cls.__func__, pre=pre, skip_on_failure=skip_on_failure)
137
+ )
138
+ return f_cls
139
+
140
+ return dec
141
+
142
+
143
+ def _prepare_validator(function: AnyCallable, allow_reuse: bool) -> 'AnyClassMethod':
144
+ """
145
+ Avoid validators with duplicated names since without this, validators can be overwritten silently
146
+ which generally isn't the intended behaviour, don't run in ipython (see #312) or if allow_reuse is False.
147
+ """
148
+ f_cls = function if isinstance(function, classmethod) else classmethod(function)
149
+ if not in_ipython() and not allow_reuse:
150
+ ref = (
151
+ getattr(f_cls.__func__, '__module__', '<No __module__>')
152
+ + '.'
153
+ + getattr(f_cls.__func__, '__qualname__', f'<No __qualname__: id:{id(f_cls.__func__)}>')
154
+ )
155
+ if ref in _FUNCS:
156
+ raise ConfigError(f'duplicate validator function "{ref}"; if this is intended, set `allow_reuse=True`')
157
+ _FUNCS.add(ref)
158
+ return f_cls
159
+
160
+
161
+ class ValidatorGroup:
162
+ def __init__(self, validators: 'ValidatorListDict') -> None:
163
+ self.validators = validators
164
+ self.used_validators = {'*'}
165
+
166
+ def get_validators(self, name: str) -> Optional[Dict[str, Validator]]:
167
+ self.used_validators.add(name)
168
+ validators = self.validators.get(name, [])
169
+ if name != ROOT_KEY:
170
+ validators += self.validators.get('*', [])
171
+ if validators:
172
+ return {getattr(v.func, '__name__', f'<No __name__: id:{id(v.func)}>'): v for v in validators}
173
+ else:
174
+ return None
175
+
176
+ def check_for_unused(self) -> None:
177
+ unused_validators = set(
178
+ chain.from_iterable(
179
+ (
180
+ getattr(v.func, '__name__', f'<No __name__: id:{id(v.func)}>')
181
+ for v in self.validators[f]
182
+ if v.check_fields
183
+ )
184
+ for f in (self.validators.keys() - self.used_validators)
185
+ )
186
+ )
187
+ if unused_validators:
188
+ fn = ', '.join(unused_validators)
189
+ raise ConfigError(
190
+ f"Validators defined with incorrect fields: {fn} " # noqa: Q000
191
+ f"(use check_fields=False if you're inheriting from the model and intended this)"
192
+ )
193
+
194
+
195
+ def extract_validators(namespace: Dict[str, Any]) -> Dict[str, List[Validator]]:
196
+ validators: Dict[str, List[Validator]] = {}
197
+ for var_name, value in namespace.items():
198
+ validator_config = getattr(value, VALIDATOR_CONFIG_KEY, None)
199
+ if validator_config:
200
+ fields, v = validator_config
201
+ for field in fields:
202
+ if field in validators:
203
+ validators[field].append(v)
204
+ else:
205
+ validators[field] = [v]
206
+ return validators
207
+
208
+
209
+ def extract_root_validators(namespace: Dict[str, Any]) -> Tuple[List[AnyCallable], List[Tuple[bool, AnyCallable]]]:
210
+ from inspect import signature
211
+
212
+ pre_validators: List[AnyCallable] = []
213
+ post_validators: List[Tuple[bool, AnyCallable]] = []
214
+ for name, value in namespace.items():
215
+ validator_config: Optional[Validator] = getattr(value, ROOT_VALIDATOR_CONFIG_KEY, None)
216
+ if validator_config:
217
+ sig = signature(validator_config.func)
218
+ args = list(sig.parameters.keys())
219
+ if args[0] == 'self':
220
+ raise ConfigError(
221
+ f'Invalid signature for root validator {name}: {sig}, "self" not permitted as first argument, '
222
+ f'should be: (cls, values).'
223
+ )
224
+ if len(args) != 2:
225
+ raise ConfigError(f'Invalid signature for root validator {name}: {sig}, should be: (cls, values).')
226
+ # check function signature
227
+ if validator_config.pre:
228
+ pre_validators.append(validator_config.func)
229
+ else:
230
+ post_validators.append((validator_config.skip_on_failure, validator_config.func))
231
+ return pre_validators, post_validators
232
+
233
+
234
+ def inherit_validators(base_validators: 'ValidatorListDict', validators: 'ValidatorListDict') -> 'ValidatorListDict':
235
+ for field, field_validators in base_validators.items():
236
+ if field not in validators:
237
+ validators[field] = []
238
+ validators[field] += field_validators
239
+ return validators
240
+
241
+
242
+ def make_generic_validator(validator: AnyCallable) -> 'ValidatorCallable':
243
+ """
244
+ Make a generic function which calls a validator with the right arguments.
245
+
246
+ Unfortunately other approaches (eg. return a partial of a function that builds the arguments) is slow,
247
+ hence this laborious way of doing things.
248
+
249
+ It's done like this so validators don't all need **kwargs in their signature, eg. any combination of
250
+ the arguments "values", "fields" and/or "config" are permitted.
251
+ """
252
+ from inspect import signature
253
+
254
+ if not isinstance(validator, (partial, partialmethod)):
255
+ # This should be the default case, so overhead is reduced
256
+ sig = signature(validator)
257
+ args = list(sig.parameters.keys())
258
+ else:
259
+ # Fix the generated argument lists of partial methods
260
+ sig = signature(validator.func)
261
+ args = [
262
+ k
263
+ for k in signature(validator.func).parameters.keys()
264
+ if k not in validator.args | validator.keywords.keys()
265
+ ]
266
+
267
+ first_arg = args.pop(0)
268
+ if first_arg == 'self':
269
+ raise ConfigError(
270
+ f'Invalid signature for validator {validator}: {sig}, "self" not permitted as first argument, '
271
+ f'should be: (cls, value, values, config, field), "values", "config" and "field" are all optional.'
272
+ )
273
+ elif first_arg == 'cls':
274
+ # assume the second argument is value
275
+ return wraps(validator)(_generic_validator_cls(validator, sig, set(args[1:])))
276
+ else:
277
+ # assume the first argument was value which has already been removed
278
+ return wraps(validator)(_generic_validator_basic(validator, sig, set(args)))
279
+
280
+
281
+ def prep_validators(v_funcs: Iterable[AnyCallable]) -> 'ValidatorsList':
282
+ return [make_generic_validator(f) for f in v_funcs if f]
283
+
284
+
285
+ all_kwargs = {'values', 'field', 'config'}
286
+
287
+
288
+ def _generic_validator_cls(validator: AnyCallable, sig: 'Signature', args: Set[str]) -> 'ValidatorCallable':
289
+ # assume the first argument is value
290
+ has_kwargs = False
291
+ if 'kwargs' in args:
292
+ has_kwargs = True
293
+ args -= {'kwargs'}
294
+
295
+ if not args.issubset(all_kwargs):
296
+ raise ConfigError(
297
+ f'Invalid signature for validator {validator}: {sig}, should be: '
298
+ f'(cls, value, values, config, field), "values", "config" and "field" are all optional.'
299
+ )
300
+
301
+ if has_kwargs:
302
+ return lambda cls, v, values, field, config: validator(cls, v, values=values, field=field, config=config)
303
+ elif args == set():
304
+ return lambda cls, v, values, field, config: validator(cls, v)
305
+ elif args == {'values'}:
306
+ return lambda cls, v, values, field, config: validator(cls, v, values=values)
307
+ elif args == {'field'}:
308
+ return lambda cls, v, values, field, config: validator(cls, v, field=field)
309
+ elif args == {'config'}:
310
+ return lambda cls, v, values, field, config: validator(cls, v, config=config)
311
+ elif args == {'values', 'field'}:
312
+ return lambda cls, v, values, field, config: validator(cls, v, values=values, field=field)
313
+ elif args == {'values', 'config'}:
314
+ return lambda cls, v, values, field, config: validator(cls, v, values=values, config=config)
315
+ elif args == {'field', 'config'}:
316
+ return lambda cls, v, values, field, config: validator(cls, v, field=field, config=config)
317
+ else:
318
+ # args == {'values', 'field', 'config'}
319
+ return lambda cls, v, values, field, config: validator(cls, v, values=values, field=field, config=config)
320
+
321
+
322
+ def _generic_validator_basic(validator: AnyCallable, sig: 'Signature', args: Set[str]) -> 'ValidatorCallable':
323
+ has_kwargs = False
324
+ if 'kwargs' in args:
325
+ has_kwargs = True
326
+ args -= {'kwargs'}
327
+
328
+ if not args.issubset(all_kwargs):
329
+ raise ConfigError(
330
+ f'Invalid signature for validator {validator}: {sig}, should be: '
331
+ f'(value, values, config, field), "values", "config" and "field" are all optional.'
332
+ )
333
+
334
+ if has_kwargs:
335
+ return lambda cls, v, values, field, config: validator(v, values=values, field=field, config=config)
336
+ elif args == set():
337
+ return lambda cls, v, values, field, config: validator(v)
338
+ elif args == {'values'}:
339
+ return lambda cls, v, values, field, config: validator(v, values=values)
340
+ elif args == {'field'}:
341
+ return lambda cls, v, values, field, config: validator(v, field=field)
342
+ elif args == {'config'}:
343
+ return lambda cls, v, values, field, config: validator(v, config=config)
344
+ elif args == {'values', 'field'}:
345
+ return lambda cls, v, values, field, config: validator(v, values=values, field=field)
346
+ elif args == {'values', 'config'}:
347
+ return lambda cls, v, values, field, config: validator(v, values=values, config=config)
348
+ elif args == {'field', 'config'}:
349
+ return lambda cls, v, values, field, config: validator(v, field=field, config=config)
350
+ else:
351
+ # args == {'values', 'field', 'config'}
352
+ return lambda cls, v, values, field, config: validator(v, values=values, field=field, config=config)
353
+
354
+
355
+ def gather_all_validators(type_: 'ModelOrDc') -> Dict[str, 'AnyClassMethod']:
356
+ all_attributes = ChainMap(*[cls.__dict__ for cls in type_.__mro__]) # type: ignore[arg-type,var-annotated]
357
+ return {
358
+ k: v
359
+ for k, v in all_attributes.items()
360
+ if hasattr(v, VALIDATOR_CONFIG_KEY) or hasattr(v, ROOT_VALIDATOR_CONFIG_KEY)
361
+ }