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,1130 @@
1
+ import sys
2
+ import warnings
3
+ from abc import ABCMeta
4
+ from copy import deepcopy
5
+ from enum import Enum
6
+ from functools import partial
7
+ from pathlib import Path
8
+ from types import FunctionType, prepare_class, resolve_bases
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ AbstractSet,
12
+ Any,
13
+ Callable,
14
+ ClassVar,
15
+ Dict,
16
+ List,
17
+ Mapping,
18
+ Optional,
19
+ Tuple,
20
+ Type,
21
+ TypeVar,
22
+ Union,
23
+ cast,
24
+ no_type_check,
25
+ overload,
26
+ )
27
+
28
+ from typing_extensions import dataclass_transform
29
+
30
+ from pboot_validator.v1.class_validators import ValidatorGroup, extract_root_validators, extract_validators, inherit_validators
31
+ from pboot_validator.v1.config import BaseConfig, Extra, inherit_config, prepare_config
32
+ from pboot_validator.v1.error_wrappers import ErrorWrapper, ValidationError
33
+ from pboot_validator.v1.errors import ConfigError, DictError, ExtraError, MissingError
34
+ from pboot_validator.v1.fields import (
35
+ MAPPING_LIKE_SHAPES,
36
+ Field,
37
+ ModelField,
38
+ ModelPrivateAttr,
39
+ PrivateAttr,
40
+ Undefined,
41
+ is_finalvar_with_default_val,
42
+ )
43
+ from pboot_validator.v1.json import custom_pydantic_encoder, pydantic_encoder
44
+ from pboot_validator.v1.parse import Protocol, load_file, load_str_bytes
45
+ from pboot_validator.v1.schema import default_ref_template, model_schema
46
+ from pboot_validator.v1.types import PyObject, StrBytes
47
+ from pboot_validator.v1.typing import (
48
+ AnyCallable,
49
+ get_args,
50
+ get_origin,
51
+ is_classvar,
52
+ is_namedtuple,
53
+ is_union,
54
+ resolve_annotations,
55
+ update_model_forward_refs,
56
+ )
57
+ from pboot_validator.v1.utils import (
58
+ DUNDER_ATTRIBUTES,
59
+ ROOT_KEY,
60
+ ClassAttribute,
61
+ GetterDict,
62
+ Representation,
63
+ ValueItems,
64
+ generate_model_signature,
65
+ is_valid_field,
66
+ is_valid_private_name,
67
+ lenient_issubclass,
68
+ sequence_like,
69
+ smart_deepcopy,
70
+ unique_list,
71
+ validate_field_name,
72
+ )
73
+
74
+ if TYPE_CHECKING:
75
+ from inspect import Signature
76
+
77
+ from pboot_validator.v1.class_validators import ValidatorListDict
78
+ from pboot_validator.v1.types import ModelOrDc
79
+ from pboot_validator.v1.typing import (
80
+ AbstractSetIntStr,
81
+ AnyClassMethod,
82
+ CallableGenerator,
83
+ DictAny,
84
+ DictStrAny,
85
+ MappingIntStrAny,
86
+ ReprArgs,
87
+ SetStr,
88
+ TupleGenerator,
89
+ )
90
+
91
+ Model = TypeVar('Model', bound='BaseModel')
92
+
93
+ __all__ = 'BaseModel', 'create_model', 'validate_model'
94
+
95
+ _T = TypeVar('_T')
96
+
97
+
98
+ def validate_custom_root_type(fields: Dict[str, ModelField]) -> None:
99
+ if len(fields) > 1:
100
+ raise ValueError(f'{ROOT_KEY} cannot be mixed with other fields')
101
+
102
+
103
+ def generate_hash_function(frozen: bool) -> Optional[Callable[[Any], int]]:
104
+ def hash_function(self_: Any) -> int:
105
+ return hash(self_.__class__) + hash(tuple(self_.__dict__.values()))
106
+
107
+ return hash_function if frozen else None
108
+
109
+
110
+ # If a field is of type `Callable`, its default value should be a function and cannot to ignored.
111
+ ANNOTATED_FIELD_UNTOUCHED_TYPES: Tuple[Any, ...] = (property, type, classmethod, staticmethod)
112
+ # When creating a `BaseModel` instance, we bypass all the methods, properties... added to the model
113
+ UNTOUCHED_TYPES: Tuple[Any, ...] = (FunctionType,) + ANNOTATED_FIELD_UNTOUCHED_TYPES
114
+ # Note `ModelMetaclass` refers to `BaseModel`, but is also used to *create* `BaseModel`, so we need to add this extra
115
+ # (somewhat hacky) boolean to keep track of whether we've created the `BaseModel` class yet, and therefore whether it's
116
+ # safe to refer to it. If it *hasn't* been created, we assume that the `__new__` call we're in the middle of is for
117
+ # the `BaseModel` class, since that's defined immediately after the metaclass.
118
+ _is_base_model_class_defined = False
119
+
120
+
121
+ @dataclass_transform(kw_only_default=True, field_specifiers=(Field,))
122
+ class ModelMetaclass(ABCMeta):
123
+ @no_type_check # noqa C901
124
+ def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901
125
+ fields: Dict[str, ModelField] = {}
126
+ config = BaseConfig
127
+ validators: 'ValidatorListDict' = {}
128
+
129
+ pre_root_validators, post_root_validators = [], []
130
+ private_attributes: Dict[str, ModelPrivateAttr] = {}
131
+ base_private_attributes: Dict[str, ModelPrivateAttr] = {}
132
+ slots: SetStr = namespace.get('__slots__', ())
133
+ slots = {slots} if isinstance(slots, str) else set(slots)
134
+ class_vars: SetStr = set()
135
+ hash_func: Optional[Callable[[Any], int]] = None
136
+
137
+ for base in reversed(bases):
138
+ if _is_base_model_class_defined and issubclass(base, BaseModel) and base != BaseModel:
139
+ fields.update(smart_deepcopy(base.__fields__))
140
+ config = inherit_config(base.__config__, config)
141
+ validators = inherit_validators(base.__validators__, validators)
142
+ pre_root_validators += base.__pre_root_validators__
143
+ post_root_validators += base.__post_root_validators__
144
+ base_private_attributes.update(base.__private_attributes__)
145
+ class_vars.update(base.__class_vars__)
146
+ hash_func = base.__hash__
147
+
148
+ resolve_forward_refs = kwargs.pop('__resolve_forward_refs__', True)
149
+ allowed_config_kwargs: SetStr = {
150
+ key
151
+ for key in dir(config)
152
+ if not (key.startswith('__') and key.endswith('__')) # skip dunder methods and attributes
153
+ }
154
+ config_kwargs = {key: kwargs.pop(key) for key in kwargs.keys() & allowed_config_kwargs}
155
+ config_from_namespace = namespace.get('Config')
156
+ if config_kwargs and config_from_namespace:
157
+ raise TypeError('Specifying config in two places is ambiguous, use either Config attribute or class kwargs')
158
+ config = inherit_config(config_from_namespace, config, **config_kwargs)
159
+
160
+ validators = inherit_validators(extract_validators(namespace), validators)
161
+ vg = ValidatorGroup(validators)
162
+
163
+ for f in fields.values():
164
+ f.set_config(config)
165
+ extra_validators = vg.get_validators(f.name)
166
+ if extra_validators:
167
+ f.class_validators.update(extra_validators)
168
+ # re-run prepare to add extra validators
169
+ f.populate_validators()
170
+
171
+ prepare_config(config, name)
172
+
173
+ untouched_types = ANNOTATED_FIELD_UNTOUCHED_TYPES
174
+
175
+ def is_untouched(v: Any) -> bool:
176
+ return isinstance(v, untouched_types) or v.__class__.__name__ == 'cython_function_or_method'
177
+
178
+ if (namespace.get('__module__'), namespace.get('__qualname__')) != ('pboot_validator.main', 'BaseModel'):
179
+ if sys.version_info >= (3, 14):
180
+ if '__annotations__' in namespace:
181
+ # `from __future__ import annotations` was used in the model's module
182
+ raw_annotations = namespace['__annotations__']
183
+ else:
184
+ # See https://docs.python.org/3/library/annotationlib.html#using-annotations-in-a-metaclass:
185
+ from annotationlib import Format, call_annotate_function, get_annotate_from_class_namespace
186
+
187
+ annotate = get_annotate_from_class_namespace(namespace)
188
+ if annotate is not None:
189
+ raw_annotations = call_annotate_function(annotate, format=Format.FORWARDREF)
190
+ else:
191
+ raw_annotations = {}
192
+ else:
193
+ raw_annotations = namespace.get('__annotations__', {})
194
+
195
+ annotations = resolve_annotations(raw_annotations, namespace.get('__module__', None))
196
+ # annotation only fields need to come first in fields
197
+ for ann_name, ann_type in annotations.items():
198
+ if is_classvar(ann_type):
199
+ class_vars.add(ann_name)
200
+ elif is_finalvar_with_default_val(ann_type, namespace.get(ann_name, Undefined)):
201
+ class_vars.add(ann_name)
202
+ elif is_valid_field(ann_name):
203
+ validate_field_name(bases, ann_name)
204
+ value = namespace.get(ann_name, Undefined)
205
+ allowed_types = get_args(ann_type) if is_union(get_origin(ann_type)) else (ann_type,)
206
+ if (
207
+ is_untouched(value)
208
+ and ann_type != PyObject
209
+ and not any(
210
+ lenient_issubclass(get_origin(allowed_type), Type) for allowed_type in allowed_types
211
+ )
212
+ ):
213
+ continue
214
+ fields[ann_name] = ModelField.infer(
215
+ name=ann_name,
216
+ value=value,
217
+ annotation=ann_type,
218
+ class_validators=vg.get_validators(ann_name),
219
+ config=config,
220
+ )
221
+ elif ann_name not in namespace and config.underscore_attrs_are_private:
222
+ private_attributes[ann_name] = PrivateAttr()
223
+
224
+ untouched_types = UNTOUCHED_TYPES + config.keep_untouched
225
+ for var_name, value in namespace.items():
226
+ can_be_changed = var_name not in class_vars and not is_untouched(value)
227
+ if isinstance(value, ModelPrivateAttr):
228
+ if not is_valid_private_name(var_name):
229
+ raise NameError(
230
+ f'Private attributes "{var_name}" must not be a valid field name; '
231
+ f'Use sunder or dunder names, e. g. "_{var_name}" or "__{var_name}__"'
232
+ )
233
+ private_attributes[var_name] = value
234
+ elif config.underscore_attrs_are_private and is_valid_private_name(var_name) and can_be_changed:
235
+ private_attributes[var_name] = PrivateAttr(default=value)
236
+ elif is_valid_field(var_name) and var_name not in annotations and can_be_changed:
237
+ validate_field_name(bases, var_name)
238
+ inferred = ModelField.infer(
239
+ name=var_name,
240
+ value=value,
241
+ annotation=annotations.get(var_name, Undefined),
242
+ class_validators=vg.get_validators(var_name),
243
+ config=config,
244
+ )
245
+ if var_name in fields:
246
+ if lenient_issubclass(inferred.type_, fields[var_name].type_):
247
+ inferred.type_ = fields[var_name].type_
248
+ else:
249
+ raise TypeError(
250
+ f'The type of {name}.{var_name} differs from the new default value; '
251
+ f'if you wish to change the type of this field, please use a type annotation'
252
+ )
253
+ fields[var_name] = inferred
254
+
255
+ _custom_root_type = ROOT_KEY in fields
256
+ if _custom_root_type:
257
+ validate_custom_root_type(fields)
258
+ vg.check_for_unused()
259
+ if config.json_encoders:
260
+ json_encoder = partial(custom_pydantic_encoder, config.json_encoders)
261
+ else:
262
+ json_encoder = pydantic_encoder
263
+ pre_rv_new, post_rv_new = extract_root_validators(namespace)
264
+
265
+ if hash_func is None:
266
+ hash_func = generate_hash_function(config.frozen)
267
+
268
+ exclude_from_namespace = fields | private_attributes.keys() | {'__slots__'}
269
+ new_namespace = {
270
+ '__config__': config,
271
+ '__fields__': fields,
272
+ '__exclude_fields__': {
273
+ name: field.field_info.exclude for name, field in fields.items() if field.field_info.exclude is not None
274
+ }
275
+ or None,
276
+ '__include_fields__': {
277
+ name: field.field_info.include for name, field in fields.items() if field.field_info.include is not None
278
+ }
279
+ or None,
280
+ '__validators__': vg.validators,
281
+ '__pre_root_validators__': unique_list(
282
+ pre_root_validators + pre_rv_new,
283
+ name_factory=lambda v: v.__name__,
284
+ ),
285
+ '__post_root_validators__': unique_list(
286
+ post_root_validators + post_rv_new,
287
+ name_factory=lambda skip_on_failure_and_v: skip_on_failure_and_v[1].__name__,
288
+ ),
289
+ '__schema_cache__': {},
290
+ '__json_encoder__': staticmethod(json_encoder),
291
+ '__custom_root_type__': _custom_root_type,
292
+ '__private_attributes__': {**base_private_attributes, **private_attributes},
293
+ '__slots__': slots | private_attributes.keys(),
294
+ '__hash__': hash_func,
295
+ '__class_vars__': class_vars,
296
+ **{n: v for n, v in namespace.items() if n not in exclude_from_namespace},
297
+ }
298
+
299
+ cls = super().__new__(mcs, name, bases, new_namespace, **kwargs)
300
+ # set __signature__ attr only for model class, but not for its instances
301
+ cls.__signature__ = ClassAttribute('__signature__', generate_model_signature(cls.__init__, fields, config))
302
+
303
+ if not _is_base_model_class_defined:
304
+ # Cython does not understand the `if TYPE_CHECKING:` condition in the
305
+ # BaseModel's body (where annotations are set), so clear them manually:
306
+ getattr(cls, '__annotations__', {}).clear()
307
+
308
+ if resolve_forward_refs:
309
+ cls.__try_update_forward_refs__()
310
+
311
+ # preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487
312
+ # for attributes not in `new_namespace` (e.g. private attributes)
313
+ for name, obj in namespace.items():
314
+ if name not in new_namespace:
315
+ set_name = getattr(obj, '__set_name__', None)
316
+ if callable(set_name):
317
+ set_name(cls, name)
318
+
319
+ return cls
320
+
321
+ def __instancecheck__(self, instance: Any) -> bool:
322
+ """
323
+ Avoid calling ABC _abc_subclasscheck unless we're pretty sure.
324
+
325
+ See #3829 and python/cpython#92810
326
+ """
327
+ return hasattr(instance, '__post_root_validators__') and super().__instancecheck__(instance)
328
+
329
+
330
+ object_setattr = object.__setattr__
331
+
332
+
333
+ class BaseModel(Representation, metaclass=ModelMetaclass):
334
+ if TYPE_CHECKING:
335
+ # populated by the metaclass, defined here to help IDEs only
336
+ __fields__: ClassVar[Dict[str, ModelField]] = {}
337
+ __include_fields__: ClassVar[Optional[Mapping[str, Any]]] = None
338
+ __exclude_fields__: ClassVar[Optional[Mapping[str, Any]]] = None
339
+ __validators__: ClassVar[Dict[str, AnyCallable]] = {}
340
+ __pre_root_validators__: ClassVar[List[AnyCallable]]
341
+ __post_root_validators__: ClassVar[List[Tuple[bool, AnyCallable]]]
342
+ __config__: ClassVar[Type[BaseConfig]] = BaseConfig
343
+ __json_encoder__: ClassVar[Callable[[Any], Any]] = lambda x: x
344
+ __schema_cache__: ClassVar['DictAny'] = {}
345
+ __custom_root_type__: ClassVar[bool] = False
346
+ __signature__: ClassVar['Signature']
347
+ __private_attributes__: ClassVar[Dict[str, ModelPrivateAttr]]
348
+ __class_vars__: ClassVar[SetStr]
349
+ __fields_set__: ClassVar[SetStr] = set()
350
+
351
+ Config = BaseConfig
352
+ __slots__ = ('__dict__', '__fields_set__')
353
+ __doc__ = '' # Null out the Representation docstring
354
+
355
+ def __init__(__pydantic_self__, **data: Any) -> None:
356
+ """
357
+ Create a new model by parsing and validating input data from keyword arguments.
358
+
359
+ Raises ValidationError if the input data cannot be parsed to form a valid model.
360
+ """
361
+ # Uses something other than `self` the first arg to allow "self" as a settable attribute
362
+ values, fields_set, validation_error = validate_model(__pydantic_self__.__class__, data)
363
+ if validation_error:
364
+ raise validation_error
365
+ try:
366
+ object_setattr(__pydantic_self__, '__dict__', values)
367
+ except TypeError as e:
368
+ raise TypeError(
369
+ 'Model values must be a dict; you may not have returned a dictionary from a root validator'
370
+ ) from e
371
+ object_setattr(__pydantic_self__, '__fields_set__', fields_set)
372
+ __pydantic_self__._init_private_attributes()
373
+
374
+ @no_type_check
375
+ def __setattr__(self, name, value): # noqa: C901 (ignore complexity)
376
+ if name in self.__private_attributes__ or name in DUNDER_ATTRIBUTES:
377
+ return object_setattr(self, name, value)
378
+
379
+ if self.__config__.extra is not Extra.allow and name not in self.__fields__:
380
+ raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"')
381
+ elif not self.__config__.allow_mutation or self.__config__.frozen:
382
+ raise TypeError(f'"{self.__class__.__name__}" is immutable and does not support item assignment')
383
+ elif name in self.__fields__ and self.__fields__[name].final:
384
+ raise TypeError(
385
+ f'"{self.__class__.__name__}" object "{name}" field is final and does not support reassignment'
386
+ )
387
+ elif self.__config__.validate_assignment:
388
+ new_values = {**self.__dict__, name: value}
389
+
390
+ for validator in self.__pre_root_validators__:
391
+ try:
392
+ new_values = validator(self.__class__, new_values)
393
+ except (ValueError, TypeError, AssertionError) as exc:
394
+ raise ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], self.__class__)
395
+
396
+ known_field = self.__fields__.get(name, None)
397
+ if known_field:
398
+ # We want to
399
+ # - make sure validators are called without the current value for this field inside `values`
400
+ # - keep other values (e.g. submodels) untouched (using `BaseModel.dict()` will change them into dicts)
401
+ # - keep the order of the fields
402
+ if not known_field.field_info.allow_mutation:
403
+ raise TypeError(f'"{known_field.name}" has allow_mutation set to False and cannot be assigned')
404
+ dict_without_original_value = {k: v for k, v in self.__dict__.items() if k != name}
405
+ value, error_ = known_field.validate(value, dict_without_original_value, loc=name, cls=self.__class__)
406
+ if error_:
407
+ raise ValidationError([error_], self.__class__)
408
+ else:
409
+ new_values[name] = value
410
+
411
+ errors = []
412
+ for skip_on_failure, validator in self.__post_root_validators__:
413
+ if skip_on_failure and errors:
414
+ continue
415
+ try:
416
+ new_values = validator(self.__class__, new_values)
417
+ except (ValueError, TypeError, AssertionError) as exc:
418
+ errors.append(ErrorWrapper(exc, loc=ROOT_KEY))
419
+ if errors:
420
+ raise ValidationError(errors, self.__class__)
421
+
422
+ # update the whole __dict__ as other values than just `value`
423
+ # may be changed (e.g. with `root_validator`)
424
+ object_setattr(self, '__dict__', new_values)
425
+ else:
426
+ self.__dict__[name] = value
427
+
428
+ self.__fields_set__.add(name)
429
+
430
+ def __getstate__(self) -> 'DictAny':
431
+ private_attrs = ((k, getattr(self, k, Undefined)) for k in self.__private_attributes__)
432
+ return {
433
+ '__dict__': self.__dict__,
434
+ '__fields_set__': self.__fields_set__,
435
+ '__private_attribute_values__': {k: v for k, v in private_attrs if v is not Undefined},
436
+ }
437
+
438
+ def __setstate__(self, state: 'DictAny') -> None:
439
+ object_setattr(self, '__dict__', state['__dict__'])
440
+ object_setattr(self, '__fields_set__', state['__fields_set__'])
441
+ for name, value in state.get('__private_attribute_values__', {}).items():
442
+ object_setattr(self, name, value)
443
+
444
+ def _init_private_attributes(self) -> None:
445
+ for name, private_attr in self.__private_attributes__.items():
446
+ default = private_attr.get_default()
447
+ if default is not Undefined:
448
+ object_setattr(self, name, default)
449
+
450
+ def dict(
451
+ self,
452
+ *,
453
+ include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
454
+ exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
455
+ by_alias: bool = False,
456
+ skip_defaults: Optional[bool] = None,
457
+ exclude_unset: bool = False,
458
+ exclude_defaults: bool = False,
459
+ exclude_none: bool = False,
460
+ ) -> 'DictStrAny':
461
+ """
462
+ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
463
+
464
+ """
465
+ if skip_defaults is not None:
466
+ warnings.warn(
467
+ f'{self.__class__.__name__}.dict(): "skip_defaults" is deprecated and replaced by "exclude_unset"',
468
+ DeprecationWarning,
469
+ )
470
+ exclude_unset = skip_defaults
471
+
472
+ return dict(
473
+ self._iter(
474
+ to_dict=True,
475
+ by_alias=by_alias,
476
+ include=include,
477
+ exclude=exclude,
478
+ exclude_unset=exclude_unset,
479
+ exclude_defaults=exclude_defaults,
480
+ exclude_none=exclude_none,
481
+ )
482
+ )
483
+
484
+ def json(
485
+ self,
486
+ *,
487
+ include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
488
+ exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
489
+ by_alias: bool = False,
490
+ skip_defaults: Optional[bool] = None,
491
+ exclude_unset: bool = False,
492
+ exclude_defaults: bool = False,
493
+ exclude_none: bool = False,
494
+ encoder: Optional[Callable[[Any], Any]] = None,
495
+ models_as_dict: bool = True,
496
+ **dumps_kwargs: Any,
497
+ ) -> str:
498
+ """
499
+ Generate a JSON representation of the model, `include` and `exclude` arguments as per `dict()`.
500
+
501
+ `encoder` is an optional function to supply as `default` to json.dumps(), other arguments as per `json.dumps()`.
502
+ """
503
+ if skip_defaults is not None:
504
+ warnings.warn(
505
+ f'{self.__class__.__name__}.json(): "skip_defaults" is deprecated and replaced by "exclude_unset"',
506
+ DeprecationWarning,
507
+ )
508
+ exclude_unset = skip_defaults
509
+ encoder = cast(Callable[[Any], Any], encoder or self.__json_encoder__)
510
+
511
+ # We don't directly call `self.dict()`, which does exactly this with `to_dict=True`
512
+ # because we want to be able to keep raw `BaseModel` instances and not as `dict`.
513
+ # This allows users to write custom JSON encoders for given `BaseModel` classes.
514
+ data = dict(
515
+ self._iter(
516
+ to_dict=models_as_dict,
517
+ by_alias=by_alias,
518
+ include=include,
519
+ exclude=exclude,
520
+ exclude_unset=exclude_unset,
521
+ exclude_defaults=exclude_defaults,
522
+ exclude_none=exclude_none,
523
+ )
524
+ )
525
+ if self.__custom_root_type__:
526
+ data = data[ROOT_KEY]
527
+ return self.__config__.json_dumps(data, default=encoder, **dumps_kwargs)
528
+
529
+ @classmethod
530
+ def _enforce_dict_if_root(cls, obj: Any) -> Any:
531
+ if cls.__custom_root_type__ and (
532
+ not (isinstance(obj, dict) and obj.keys() == {ROOT_KEY})
533
+ and not (isinstance(obj, BaseModel) and obj.__fields__.keys() == {ROOT_KEY})
534
+ or cls.__fields__[ROOT_KEY].shape in MAPPING_LIKE_SHAPES
535
+ ):
536
+ return {ROOT_KEY: obj}
537
+ else:
538
+ return obj
539
+
540
+ @classmethod
541
+ def parse_obj(cls: Type['Model'], obj: Any) -> 'Model':
542
+ obj = cls._enforce_dict_if_root(obj)
543
+ if not isinstance(obj, dict):
544
+ try:
545
+ obj = dict(obj)
546
+ except (TypeError, ValueError) as e:
547
+ exc = TypeError(f'{cls.__name__} expected dict not {obj.__class__.__name__}')
548
+ raise ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls) from e
549
+ return cls(**obj)
550
+
551
+ @classmethod
552
+ def parse_raw(
553
+ cls: Type['Model'],
554
+ b: StrBytes,
555
+ *,
556
+ content_type: str = None,
557
+ encoding: str = 'utf8',
558
+ proto: Protocol = None,
559
+ allow_pickle: bool = False,
560
+ ) -> 'Model':
561
+ try:
562
+ obj = load_str_bytes(
563
+ b,
564
+ proto=proto,
565
+ content_type=content_type,
566
+ encoding=encoding,
567
+ allow_pickle=allow_pickle,
568
+ json_loads=cls.__config__.json_loads,
569
+ )
570
+ except (ValueError, TypeError, UnicodeDecodeError) as e:
571
+ raise ValidationError([ErrorWrapper(e, loc=ROOT_KEY)], cls)
572
+ return cls.parse_obj(obj)
573
+
574
+ @classmethod
575
+ def parse_file(
576
+ cls: Type['Model'],
577
+ path: Union[str, Path],
578
+ *,
579
+ content_type: str = None,
580
+ encoding: str = 'utf8',
581
+ proto: Protocol = None,
582
+ allow_pickle: bool = False,
583
+ ) -> 'Model':
584
+ obj = load_file(
585
+ path,
586
+ proto=proto,
587
+ content_type=content_type,
588
+ encoding=encoding,
589
+ allow_pickle=allow_pickle,
590
+ json_loads=cls.__config__.json_loads,
591
+ )
592
+ return cls.parse_obj(obj)
593
+
594
+ @classmethod
595
+ def from_orm(cls: Type['Model'], obj: Any) -> 'Model':
596
+ if not cls.__config__.orm_mode:
597
+ raise ConfigError('You must have the config attribute orm_mode=True to use from_orm')
598
+ obj = {ROOT_KEY: obj} if cls.__custom_root_type__ else cls._decompose_class(obj)
599
+ m = cls.__new__(cls)
600
+ values, fields_set, validation_error = validate_model(cls, obj)
601
+ if validation_error:
602
+ raise validation_error
603
+ object_setattr(m, '__dict__', values)
604
+ object_setattr(m, '__fields_set__', fields_set)
605
+ m._init_private_attributes()
606
+ return m
607
+
608
+ @classmethod
609
+ def construct(cls: Type['Model'], _fields_set: Optional['SetStr'] = None, **values: Any) -> 'Model':
610
+ """
611
+ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
612
+ Default values are respected, but no other validation is performed.
613
+ Behaves as if `Config.extra = 'allow'` was set since it adds all passed values
614
+ """
615
+ m = cls.__new__(cls)
616
+ fields_values: Dict[str, Any] = {}
617
+ for name, field in cls.__fields__.items():
618
+ if field.alt_alias and field.alias in values:
619
+ fields_values[name] = values[field.alias]
620
+ elif name in values:
621
+ fields_values[name] = values[name]
622
+ elif not field.required:
623
+ fields_values[name] = field.get_default()
624
+ fields_values.update(values)
625
+ object_setattr(m, '__dict__', fields_values)
626
+ if _fields_set is None:
627
+ _fields_set = set(values.keys())
628
+ object_setattr(m, '__fields_set__', _fields_set)
629
+ m._init_private_attributes()
630
+ return m
631
+
632
+ def _copy_and_set_values(self: 'Model', values: 'DictStrAny', fields_set: 'SetStr', *, deep: bool) -> 'Model':
633
+ if deep:
634
+ # chances of having empty dict here are quite low for using smart_deepcopy
635
+ values = deepcopy(values)
636
+
637
+ cls = self.__class__
638
+ m = cls.__new__(cls)
639
+ object_setattr(m, '__dict__', values)
640
+ object_setattr(m, '__fields_set__', fields_set)
641
+ for name in self.__private_attributes__:
642
+ value = getattr(self, name, Undefined)
643
+ if value is not Undefined:
644
+ if deep:
645
+ value = deepcopy(value)
646
+ object_setattr(m, name, value)
647
+
648
+ return m
649
+
650
+ def copy(
651
+ self: 'Model',
652
+ *,
653
+ include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
654
+ exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
655
+ update: Optional['DictStrAny'] = None,
656
+ deep: bool = False,
657
+ ) -> 'Model':
658
+ """
659
+ Duplicate a model, optionally choose which fields to include, exclude and change.
660
+
661
+ :param include: fields to include in new model
662
+ :param exclude: fields to exclude from new model, as with values this takes precedence over include
663
+ :param update: values to change/add in the new model. Note: the data is not validated before creating
664
+ the new model: you should trust this data
665
+ :param deep: set to `True` to make a deep copy of the model
666
+ :return: new model instance
667
+ """
668
+
669
+ values = dict(
670
+ self._iter(to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False),
671
+ **(update or {}),
672
+ )
673
+
674
+ # new `__fields_set__` can have unset optional fields with a set value in `update` kwarg
675
+ if update:
676
+ fields_set = self.__fields_set__ | update.keys()
677
+ else:
678
+ fields_set = set(self.__fields_set__)
679
+
680
+ return self._copy_and_set_values(values, fields_set, deep=deep)
681
+
682
+ @classmethod
683
+ def schema(cls, by_alias: bool = True, ref_template: str = default_ref_template) -> 'DictStrAny':
684
+ cached = cls.__schema_cache__.get((by_alias, ref_template))
685
+ if cached is not None:
686
+ return cached
687
+ s = model_schema(cls, by_alias=by_alias, ref_template=ref_template)
688
+ cls.__schema_cache__[(by_alias, ref_template)] = s
689
+ return s
690
+
691
+ @classmethod
692
+ def schema_json(
693
+ cls, *, by_alias: bool = True, ref_template: str = default_ref_template, **dumps_kwargs: Any
694
+ ) -> str:
695
+ from pboot_validator.v1.json import pydantic_encoder
696
+
697
+ return cls.__config__.json_dumps(
698
+ cls.schema(by_alias=by_alias, ref_template=ref_template), default=pydantic_encoder, **dumps_kwargs
699
+ )
700
+
701
+ @classmethod
702
+ def __get_validators__(cls) -> 'CallableGenerator':
703
+ yield cls.validate
704
+
705
+ @classmethod
706
+ def validate(cls: Type['Model'], value: Any) -> 'Model':
707
+ if isinstance(value, cls):
708
+ copy_on_model_validation = cls.__config__.copy_on_model_validation
709
+ # whether to deep or shallow copy the model on validation, None means do not copy
710
+ deep_copy: Optional[bool] = None
711
+ if copy_on_model_validation not in {'deep', 'shallow', 'none'}:
712
+ # Warn about deprecated behavior
713
+ warnings.warn(
714
+ "`copy_on_model_validation` should be a string: 'deep', 'shallow' or 'none'", DeprecationWarning
715
+ )
716
+ if copy_on_model_validation:
717
+ deep_copy = False
718
+
719
+ if copy_on_model_validation == 'shallow':
720
+ # shallow copy
721
+ deep_copy = False
722
+ elif copy_on_model_validation == 'deep':
723
+ # deep copy
724
+ deep_copy = True
725
+
726
+ if deep_copy is None:
727
+ return value
728
+ else:
729
+ return value._copy_and_set_values(value.__dict__, value.__fields_set__, deep=deep_copy)
730
+
731
+ value = cls._enforce_dict_if_root(value)
732
+
733
+ if isinstance(value, dict):
734
+ return cls(**value)
735
+ elif cls.__config__.orm_mode:
736
+ return cls.from_orm(value)
737
+ else:
738
+ try:
739
+ value_as_dict = dict(value)
740
+ except (TypeError, ValueError) as e:
741
+ raise DictError() from e
742
+ return cls(**value_as_dict)
743
+
744
+ @classmethod
745
+ def _decompose_class(cls: Type['Model'], obj: Any) -> GetterDict:
746
+ if isinstance(obj, GetterDict):
747
+ return obj
748
+ return cls.__config__.getter_dict(obj)
749
+
750
+ @classmethod
751
+ @no_type_check
752
+ def _get_value(
753
+ cls,
754
+ v: Any,
755
+ to_dict: bool,
756
+ by_alias: bool,
757
+ include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']],
758
+ exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']],
759
+ exclude_unset: bool,
760
+ exclude_defaults: bool,
761
+ exclude_none: bool,
762
+ ) -> Any:
763
+ if isinstance(v, BaseModel):
764
+ if to_dict:
765
+ v_dict = v.dict(
766
+ by_alias=by_alias,
767
+ exclude_unset=exclude_unset,
768
+ exclude_defaults=exclude_defaults,
769
+ include=include,
770
+ exclude=exclude,
771
+ exclude_none=exclude_none,
772
+ )
773
+ if ROOT_KEY in v_dict:
774
+ return v_dict[ROOT_KEY]
775
+ return v_dict
776
+ else:
777
+ return v.copy(include=include, exclude=exclude)
778
+
779
+ value_exclude = ValueItems(v, exclude) if exclude else None
780
+ value_include = ValueItems(v, include) if include else None
781
+
782
+ if isinstance(v, dict):
783
+ return {
784
+ k_: cls._get_value(
785
+ v_,
786
+ to_dict=to_dict,
787
+ by_alias=by_alias,
788
+ exclude_unset=exclude_unset,
789
+ exclude_defaults=exclude_defaults,
790
+ include=value_include and value_include.for_element(k_),
791
+ exclude=value_exclude and value_exclude.for_element(k_),
792
+ exclude_none=exclude_none,
793
+ )
794
+ for k_, v_ in v.items()
795
+ if (not value_exclude or not value_exclude.is_excluded(k_))
796
+ and (not value_include or value_include.is_included(k_))
797
+ }
798
+
799
+ elif sequence_like(v):
800
+ seq_args = (
801
+ cls._get_value(
802
+ v_,
803
+ to_dict=to_dict,
804
+ by_alias=by_alias,
805
+ exclude_unset=exclude_unset,
806
+ exclude_defaults=exclude_defaults,
807
+ include=value_include and value_include.for_element(i),
808
+ exclude=value_exclude and value_exclude.for_element(i),
809
+ exclude_none=exclude_none,
810
+ )
811
+ for i, v_ in enumerate(v)
812
+ if (not value_exclude or not value_exclude.is_excluded(i))
813
+ and (not value_include or value_include.is_included(i))
814
+ )
815
+
816
+ return v.__class__(*seq_args) if is_namedtuple(v.__class__) else v.__class__(seq_args)
817
+
818
+ elif isinstance(v, Enum) and getattr(cls.Config, 'use_enum_values', False):
819
+ return v.value
820
+
821
+ else:
822
+ return v
823
+
824
+ @classmethod
825
+ def __try_update_forward_refs__(cls, **localns: Any) -> None:
826
+ """
827
+ Same as update_forward_refs but will not raise exception
828
+ when forward references are not defined.
829
+ """
830
+ update_model_forward_refs(cls, cls.__fields__.values(), cls.__config__.json_encoders, localns, (NameError,))
831
+
832
+ @classmethod
833
+ def update_forward_refs(cls, **localns: Any) -> None:
834
+ """
835
+ Try to update ForwardRefs on fields based on this Model, globalns and localns.
836
+ """
837
+ update_model_forward_refs(cls, cls.__fields__.values(), cls.__config__.json_encoders, localns)
838
+
839
+ def __iter__(self) -> 'TupleGenerator':
840
+ """
841
+ so `dict(model)` works
842
+ """
843
+ yield from self.__dict__.items()
844
+
845
+ def _iter(
846
+ self,
847
+ to_dict: bool = False,
848
+ by_alias: bool = False,
849
+ include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
850
+ exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
851
+ exclude_unset: bool = False,
852
+ exclude_defaults: bool = False,
853
+ exclude_none: bool = False,
854
+ ) -> 'TupleGenerator':
855
+ # Merge field set excludes with explicit exclude parameter with explicit overriding field set options.
856
+ # The extra "is not None" guards are not logically necessary but optimizes performance for the simple case.
857
+ if exclude is not None or self.__exclude_fields__ is not None:
858
+ exclude = ValueItems.merge(self.__exclude_fields__, exclude)
859
+
860
+ if include is not None or self.__include_fields__ is not None:
861
+ include = ValueItems.merge(self.__include_fields__, include, intersect=True)
862
+
863
+ allowed_keys = self._calculate_keys(
864
+ include=include, exclude=exclude, exclude_unset=exclude_unset # type: ignore
865
+ )
866
+ if allowed_keys is None and not (to_dict or by_alias or exclude_unset or exclude_defaults or exclude_none):
867
+ # huge boost for plain _iter()
868
+ yield from self.__dict__.items()
869
+ return
870
+
871
+ value_exclude = ValueItems(self, exclude) if exclude is not None else None
872
+ value_include = ValueItems(self, include) if include is not None else None
873
+
874
+ for field_key, v in self.__dict__.items():
875
+ if (allowed_keys is not None and field_key not in allowed_keys) or (exclude_none and v is None):
876
+ continue
877
+
878
+ if exclude_defaults:
879
+ model_field = self.__fields__.get(field_key)
880
+ if not getattr(model_field, 'required', True) and getattr(model_field, 'default', _missing) == v:
881
+ continue
882
+
883
+ if by_alias and field_key in self.__fields__:
884
+ dict_key = self.__fields__[field_key].alias
885
+ else:
886
+ dict_key = field_key
887
+
888
+ if to_dict or value_include or value_exclude:
889
+ v = self._get_value(
890
+ v,
891
+ to_dict=to_dict,
892
+ by_alias=by_alias,
893
+ include=value_include and value_include.for_element(field_key),
894
+ exclude=value_exclude and value_exclude.for_element(field_key),
895
+ exclude_unset=exclude_unset,
896
+ exclude_defaults=exclude_defaults,
897
+ exclude_none=exclude_none,
898
+ )
899
+ yield dict_key, v
900
+
901
+ def _calculate_keys(
902
+ self,
903
+ include: Optional['MappingIntStrAny'],
904
+ exclude: Optional['MappingIntStrAny'],
905
+ exclude_unset: bool,
906
+ update: Optional['DictStrAny'] = None,
907
+ ) -> Optional[AbstractSet[str]]:
908
+ if include is None and exclude is None and exclude_unset is False:
909
+ return None
910
+
911
+ keys: AbstractSet[str]
912
+ if exclude_unset:
913
+ keys = self.__fields_set__.copy()
914
+ else:
915
+ keys = self.__dict__.keys()
916
+
917
+ if include is not None:
918
+ keys &= include.keys()
919
+
920
+ if update:
921
+ keys -= update.keys()
922
+
923
+ if exclude:
924
+ keys -= {k for k, v in exclude.items() if ValueItems.is_true(v)}
925
+
926
+ return keys
927
+
928
+ def __eq__(self, other: Any) -> bool:
929
+ if isinstance(other, BaseModel):
930
+ return self.dict() == other.dict()
931
+ else:
932
+ return self.dict() == other
933
+
934
+ def __repr_args__(self) -> 'ReprArgs':
935
+ return [
936
+ (k, v)
937
+ for k, v in self.__dict__.items()
938
+ if k not in DUNDER_ATTRIBUTES and (k not in self.__fields__ or self.__fields__[k].field_info.repr)
939
+ ]
940
+
941
+
942
+ _is_base_model_class_defined = True
943
+
944
+
945
+ @overload
946
+ def create_model(
947
+ __model_name: str,
948
+ *,
949
+ __config__: Optional[Type[BaseConfig]] = None,
950
+ __base__: None = None,
951
+ __module__: str = __name__,
952
+ __validators__: Dict[str, 'AnyClassMethod'] = None,
953
+ __cls_kwargs__: Dict[str, Any] = None,
954
+ **field_definitions: Any,
955
+ ) -> Type['BaseModel']:
956
+ ...
957
+
958
+
959
+ @overload
960
+ def create_model(
961
+ __model_name: str,
962
+ *,
963
+ __config__: Optional[Type[BaseConfig]] = None,
964
+ __base__: Union[Type['Model'], Tuple[Type['Model'], ...]],
965
+ __module__: str = __name__,
966
+ __validators__: Dict[str, 'AnyClassMethod'] = None,
967
+ __cls_kwargs__: Dict[str, Any] = None,
968
+ **field_definitions: Any,
969
+ ) -> Type['Model']:
970
+ ...
971
+
972
+
973
+ def create_model(
974
+ __model_name: str,
975
+ *,
976
+ __config__: Optional[Type[BaseConfig]] = None,
977
+ __base__: Union[None, Type['Model'], Tuple[Type['Model'], ...]] = None,
978
+ __module__: str = __name__,
979
+ __validators__: Dict[str, 'AnyClassMethod'] = None,
980
+ __cls_kwargs__: Dict[str, Any] = None,
981
+ __slots__: Optional[Tuple[str, ...]] = None,
982
+ **field_definitions: Any,
983
+ ) -> Type['Model']:
984
+ """
985
+ Dynamically create a model.
986
+ :param __model_name: name of the created model
987
+ :param __config__: config class to use for the new model
988
+ :param __base__: base class for the new model to inherit from
989
+ :param __module__: module of the created model
990
+ :param __validators__: a dict of method names and @validator class methods
991
+ :param __cls_kwargs__: a dict for class creation
992
+ :param __slots__: Deprecated, `__slots__` should not be passed to `create_model`
993
+ :param field_definitions: fields of the model (or extra fields if a base is supplied)
994
+ in the format `<name>=(<type>, <default default>)` or `<name>=<default value>, e.g.
995
+ `foobar=(str, ...)` or `foobar=123`, or, for complex use-cases, in the format
996
+ `<name>=<Field>` or `<name>=(<type>, <FieldInfo>)`, e.g.
997
+ `foo=Field(datetime, default_factory=datetime.utcnow, alias='bar')` or
998
+ `foo=(str, FieldInfo(title='Foo'))`
999
+ """
1000
+ if __slots__ is not None:
1001
+ # __slots__ will be ignored from here on
1002
+ warnings.warn('__slots__ should not be passed to create_model', RuntimeWarning)
1003
+
1004
+ if __base__ is not None:
1005
+ if __config__ is not None:
1006
+ raise ConfigError('to avoid confusion __config__ and __base__ cannot be used together')
1007
+ if not isinstance(__base__, tuple):
1008
+ __base__ = (__base__,)
1009
+ else:
1010
+ __base__ = (cast(Type['Model'], BaseModel),)
1011
+
1012
+ __cls_kwargs__ = __cls_kwargs__ or {}
1013
+
1014
+ fields = {}
1015
+ annotations = {}
1016
+
1017
+ for f_name, f_def in field_definitions.items():
1018
+ if not is_valid_field(f_name):
1019
+ warnings.warn(f'fields may not start with an underscore, ignoring "{f_name}"', RuntimeWarning)
1020
+ if isinstance(f_def, tuple):
1021
+ try:
1022
+ f_annotation, f_value = f_def
1023
+ except ValueError as e:
1024
+ raise ConfigError(
1025
+ 'field definitions should either be a tuple of (<type>, <default>) or just a '
1026
+ 'default value, unfortunately this means tuples as '
1027
+ 'default values are not allowed'
1028
+ ) from e
1029
+ else:
1030
+ f_annotation, f_value = None, f_def
1031
+
1032
+ if f_annotation:
1033
+ annotations[f_name] = f_annotation
1034
+ fields[f_name] = f_value
1035
+
1036
+ namespace: 'DictStrAny' = {'__annotations__': annotations, '__module__': __module__}
1037
+ if __validators__:
1038
+ namespace.update(__validators__)
1039
+ namespace.update(fields)
1040
+ if __config__:
1041
+ namespace['Config'] = inherit_config(__config__, BaseConfig)
1042
+ resolved_bases = resolve_bases(__base__)
1043
+ meta, ns, kwds = prepare_class(__model_name, resolved_bases, kwds=__cls_kwargs__)
1044
+ if resolved_bases is not __base__:
1045
+ ns['__orig_bases__'] = __base__
1046
+ namespace.update(ns)
1047
+ return meta(__model_name, resolved_bases, namespace, **kwds)
1048
+
1049
+
1050
+ _missing = object()
1051
+
1052
+
1053
+ def validate_model( # noqa: C901 (ignore complexity)
1054
+ model: Type[BaseModel], input_data: 'DictStrAny', cls: 'ModelOrDc' = None
1055
+ ) -> Tuple['DictStrAny', 'SetStr', Optional[ValidationError]]:
1056
+ """
1057
+ validate data against a model.
1058
+ """
1059
+ values = {}
1060
+ errors = []
1061
+ # input_data names, possibly alias
1062
+ names_used = set()
1063
+ # field names, never aliases
1064
+ fields_set = set()
1065
+ config = model.__config__
1066
+ check_extra = config.extra is not Extra.ignore
1067
+ cls_ = cls or model
1068
+
1069
+ for validator in model.__pre_root_validators__:
1070
+ try:
1071
+ input_data = validator(cls_, input_data)
1072
+ except (ValueError, TypeError, AssertionError) as exc:
1073
+ return {}, set(), ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls_)
1074
+
1075
+ for name, field in model.__fields__.items():
1076
+ value = input_data.get(field.alias, _missing)
1077
+ using_name = False
1078
+ if value is _missing and config.allow_population_by_field_name and field.alt_alias:
1079
+ value = input_data.get(field.name, _missing)
1080
+ using_name = True
1081
+
1082
+ if value is _missing:
1083
+ if field.required:
1084
+ errors.append(ErrorWrapper(MissingError(), loc=field.alias))
1085
+ continue
1086
+
1087
+ value = field.get_default()
1088
+
1089
+ if not config.validate_all and not field.validate_always:
1090
+ values[name] = value
1091
+ continue
1092
+ else:
1093
+ fields_set.add(name)
1094
+ if check_extra:
1095
+ names_used.add(field.name if using_name else field.alias)
1096
+
1097
+ v_, errors_ = field.validate(value, values, loc=field.alias, cls=cls_)
1098
+ if isinstance(errors_, ErrorWrapper):
1099
+ errors.append(errors_)
1100
+ elif isinstance(errors_, list):
1101
+ errors.extend(errors_)
1102
+ else:
1103
+ values[name] = v_
1104
+
1105
+ if check_extra:
1106
+ if isinstance(input_data, GetterDict):
1107
+ extra = input_data.extra_keys() - names_used
1108
+ else:
1109
+ extra = input_data.keys() - names_used
1110
+ if extra:
1111
+ fields_set |= extra
1112
+ if config.extra is Extra.allow:
1113
+ for f in extra:
1114
+ values[f] = input_data[f]
1115
+ else:
1116
+ for f in sorted(extra):
1117
+ errors.append(ErrorWrapper(ExtraError(), loc=f))
1118
+
1119
+ for skip_on_failure, validator in model.__post_root_validators__:
1120
+ if skip_on_failure and errors:
1121
+ continue
1122
+ try:
1123
+ values = validator(cls_, values)
1124
+ except (ValueError, TypeError, AssertionError) as exc:
1125
+ errors.append(ErrorWrapper(exc, loc=ROOT_KEY))
1126
+
1127
+ if errors:
1128
+ return values, fields_set, ValidationError(errors, cls_)
1129
+ else:
1130
+ return values, fields_set, None