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,503 @@
1
+ """
2
+ The main purpose is to enhance stdlib dataclasses by adding validation
3
+ A pydantic dataclass can be generated from scratch or from a stdlib one.
4
+
5
+ Behind the scene, a pydantic dataclass is just like a regular one on which we attach
6
+ a `BaseModel` and magic methods to trigger the validation of the data.
7
+ `__init__` and `__post_init__` are hence overridden and have extra logic to be
8
+ able to validate input data.
9
+
10
+ When a pydantic dataclass is generated from scratch, it's just a plain dataclass
11
+ with validation triggered at initialization
12
+
13
+ The tricky part if for stdlib dataclasses that are converted after into pydantic ones e.g.
14
+
15
+ ```py
16
+ @dataclasses.dataclass
17
+ class M:
18
+ x: int
19
+
20
+ ValidatedM = pboot_validator.dataclasses.dataclass(M)
21
+ ```
22
+
23
+ We indeed still want to support equality, hashing, repr, ... as if it was the stdlib one!
24
+
25
+ ```py
26
+ assert isinstance(ValidatedM(x=1), M)
27
+ assert ValidatedM(x=1) == M(x=1)
28
+ ```
29
+
30
+ This means we **don't want to create a new dataclass that inherits from it**
31
+ The trick is to create a wrapper around `M` that will act as a proxy to trigger
32
+ validation without altering default `M` behaviour.
33
+ """
34
+ import copy
35
+ import dataclasses
36
+ import sys
37
+ from contextlib import contextmanager
38
+ from functools import wraps
39
+
40
+ try:
41
+ from functools import cached_property
42
+ except ImportError:
43
+ # cached_property available only for python3.8+
44
+ pass
45
+
46
+ from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, Generator, Optional, Type, TypeVar, Union, overload
47
+
48
+ from typing_extensions import dataclass_transform
49
+
50
+ from pboot_validator.v1.class_validators import gather_all_validators
51
+ from pboot_validator.v1.config import BaseConfig, ConfigDict, Extra, get_config
52
+ from pboot_validator.v1.error_wrappers import ValidationError
53
+ from pboot_validator.v1.errors import DataclassTypeError
54
+ from pboot_validator.v1.fields import Field, FieldInfo, Required, Undefined
55
+ from pboot_validator.v1.main import create_model, validate_model
56
+ from pboot_validator.v1.utils import ClassAttribute
57
+
58
+ if TYPE_CHECKING:
59
+ from pboot_validator.v1.main import BaseModel
60
+ from pboot_validator.v1.typing import CallableGenerator, NoArgAnyCallable
61
+
62
+ DataclassT = TypeVar('DataclassT', bound='Dataclass')
63
+
64
+ DataclassClassOrWrapper = Union[Type['Dataclass'], 'DataclassProxy']
65
+
66
+ class Dataclass:
67
+ # stdlib attributes
68
+ __dataclass_fields__: ClassVar[Dict[str, Any]]
69
+ __dataclass_params__: ClassVar[Any] # in reality `dataclasses._DataclassParams`
70
+ __post_init__: ClassVar[Callable[..., None]]
71
+
72
+ # Added by pydantic
73
+ __pydantic_run_validation__: ClassVar[bool]
74
+ __post_init_post_parse__: ClassVar[Callable[..., None]]
75
+ __pydantic_initialised__: ClassVar[bool]
76
+ __pydantic_model__: ClassVar[Type[BaseModel]]
77
+ __pydantic_validate_values__: ClassVar[Callable[['Dataclass'], None]]
78
+ __pydantic_has_field_info_default__: ClassVar[bool] # whether a `pboot_validator.Field` is used as default value
79
+
80
+ def __init__(self, *args: object, **kwargs: object) -> None:
81
+ pass
82
+
83
+ @classmethod
84
+ def __get_validators__(cls: Type['Dataclass']) -> 'CallableGenerator':
85
+ pass
86
+
87
+ @classmethod
88
+ def __validate__(cls: Type['DataclassT'], v: Any) -> 'DataclassT':
89
+ pass
90
+
91
+
92
+ __all__ = [
93
+ 'dataclass',
94
+ 'set_validation',
95
+ 'create_pydantic_model_from_dataclass',
96
+ 'is_builtin_dataclass',
97
+ 'make_dataclass_validator',
98
+ ]
99
+
100
+ _T = TypeVar('_T')
101
+
102
+ if sys.version_info >= (3, 10):
103
+
104
+ @dataclass_transform(field_specifiers=(dataclasses.field, Field))
105
+ @overload
106
+ def dataclass(
107
+ *,
108
+ init: bool = True,
109
+ repr: bool = True,
110
+ eq: bool = True,
111
+ order: bool = False,
112
+ unsafe_hash: bool = False,
113
+ frozen: bool = False,
114
+ config: Union[ConfigDict, Type[object], None] = None,
115
+ validate_on_init: Optional[bool] = None,
116
+ use_proxy: Optional[bool] = None,
117
+ kw_only: bool = ...,
118
+ ) -> Callable[[Type[_T]], 'DataclassClassOrWrapper']:
119
+ ...
120
+
121
+ @dataclass_transform(field_specifiers=(dataclasses.field, Field))
122
+ @overload
123
+ def dataclass(
124
+ _cls: Type[_T],
125
+ *,
126
+ init: bool = True,
127
+ repr: bool = True,
128
+ eq: bool = True,
129
+ order: bool = False,
130
+ unsafe_hash: bool = False,
131
+ frozen: bool = False,
132
+ config: Union[ConfigDict, Type[object], None] = None,
133
+ validate_on_init: Optional[bool] = None,
134
+ use_proxy: Optional[bool] = None,
135
+ kw_only: bool = ...,
136
+ ) -> 'DataclassClassOrWrapper':
137
+ ...
138
+
139
+ else:
140
+
141
+ @dataclass_transform(field_specifiers=(dataclasses.field, Field))
142
+ @overload
143
+ def dataclass(
144
+ *,
145
+ init: bool = True,
146
+ repr: bool = True,
147
+ eq: bool = True,
148
+ order: bool = False,
149
+ unsafe_hash: bool = False,
150
+ frozen: bool = False,
151
+ config: Union[ConfigDict, Type[object], None] = None,
152
+ validate_on_init: Optional[bool] = None,
153
+ use_proxy: Optional[bool] = None,
154
+ ) -> Callable[[Type[_T]], 'DataclassClassOrWrapper']:
155
+ ...
156
+
157
+ @dataclass_transform(field_specifiers=(dataclasses.field, Field))
158
+ @overload
159
+ def dataclass(
160
+ _cls: Type[_T],
161
+ *,
162
+ init: bool = True,
163
+ repr: bool = True,
164
+ eq: bool = True,
165
+ order: bool = False,
166
+ unsafe_hash: bool = False,
167
+ frozen: bool = False,
168
+ config: Union[ConfigDict, Type[object], None] = None,
169
+ validate_on_init: Optional[bool] = None,
170
+ use_proxy: Optional[bool] = None,
171
+ ) -> 'DataclassClassOrWrapper':
172
+ ...
173
+
174
+
175
+ @dataclass_transform(field_specifiers=(dataclasses.field, Field))
176
+ def dataclass(
177
+ _cls: Optional[Type[_T]] = None,
178
+ *,
179
+ init: bool = True,
180
+ repr: bool = True,
181
+ eq: bool = True,
182
+ order: bool = False,
183
+ unsafe_hash: bool = False,
184
+ frozen: bool = False,
185
+ config: Union[ConfigDict, Type[object], None] = None,
186
+ validate_on_init: Optional[bool] = None,
187
+ use_proxy: Optional[bool] = None,
188
+ kw_only: bool = False,
189
+ ) -> Union[Callable[[Type[_T]], 'DataclassClassOrWrapper'], 'DataclassClassOrWrapper']:
190
+ """
191
+ Like the python standard lib dataclasses but with type validation.
192
+ The result is either a pydantic dataclass that will validate input data
193
+ or a wrapper that will trigger validation around a stdlib dataclass
194
+ to avoid modifying it directly
195
+ """
196
+ the_config = get_config(config)
197
+
198
+ def wrap(cls: Type[Any]) -> 'DataclassClassOrWrapper':
199
+ should_use_proxy = (
200
+ use_proxy
201
+ if use_proxy is not None
202
+ else (
203
+ is_builtin_dataclass(cls)
204
+ and (cls.__bases__[0] is object or set(dir(cls)) == set(dir(cls.__bases__[0])))
205
+ )
206
+ )
207
+ if should_use_proxy:
208
+ dc_cls_doc = ''
209
+ dc_cls = DataclassProxy(cls)
210
+ default_validate_on_init = False
211
+ else:
212
+ dc_cls_doc = cls.__doc__ or '' # needs to be done before generating dataclass
213
+ if sys.version_info >= (3, 10):
214
+ dc_cls = dataclasses.dataclass(
215
+ cls,
216
+ init=init,
217
+ repr=repr,
218
+ eq=eq,
219
+ order=order,
220
+ unsafe_hash=unsafe_hash,
221
+ frozen=frozen,
222
+ kw_only=kw_only,
223
+ )
224
+ else:
225
+ dc_cls = dataclasses.dataclass( # type: ignore
226
+ cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen
227
+ )
228
+ default_validate_on_init = True
229
+
230
+ should_validate_on_init = default_validate_on_init if validate_on_init is None else validate_on_init
231
+ _add_pydantic_validation_attributes(cls, the_config, should_validate_on_init, dc_cls_doc)
232
+ localns = {cls.__name__: cls}
233
+ dc_cls.__pydantic_model__.__try_update_forward_refs__(**localns)
234
+ return dc_cls
235
+
236
+ if _cls is None:
237
+ return wrap
238
+
239
+ return wrap(_cls)
240
+
241
+
242
+ @contextmanager
243
+ def set_validation(cls: Type['DataclassT'], value: bool) -> Generator[Type['DataclassT'], None, None]:
244
+ original_run_validation = cls.__pydantic_run_validation__
245
+ try:
246
+ cls.__pydantic_run_validation__ = value
247
+ yield cls
248
+ finally:
249
+ cls.__pydantic_run_validation__ = original_run_validation
250
+
251
+
252
+ class DataclassProxy:
253
+ __slots__ = '__dataclass__'
254
+
255
+ def __init__(self, dc_cls: Type['Dataclass']) -> None:
256
+ object.__setattr__(self, '__dataclass__', dc_cls)
257
+
258
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
259
+ with set_validation(self.__dataclass__, True):
260
+ return self.__dataclass__(*args, **kwargs)
261
+
262
+ def __getattr__(self, name: str) -> Any:
263
+ return getattr(self.__dataclass__, name)
264
+
265
+ def __setattr__(self, __name: str, __value: Any) -> None:
266
+ return setattr(self.__dataclass__, __name, __value)
267
+
268
+ def __instancecheck__(self, instance: Any) -> bool:
269
+ return isinstance(instance, self.__dataclass__)
270
+
271
+ def __copy__(self) -> 'DataclassProxy':
272
+ return DataclassProxy(copy.copy(self.__dataclass__))
273
+
274
+ def __deepcopy__(self, memo: Any) -> 'DataclassProxy':
275
+ return DataclassProxy(copy.deepcopy(self.__dataclass__, memo))
276
+
277
+
278
+ def _add_pydantic_validation_attributes( # noqa: C901 (ignore complexity)
279
+ dc_cls: Type['Dataclass'],
280
+ config: Type[BaseConfig],
281
+ validate_on_init: bool,
282
+ dc_cls_doc: str,
283
+ ) -> None:
284
+ """
285
+ We need to replace the right method. If no `__post_init__` has been set in the stdlib dataclass
286
+ it won't even exist (code is generated on the fly by `dataclasses`)
287
+ By default, we run validation after `__init__` or `__post_init__` if defined
288
+ """
289
+ init = dc_cls.__init__
290
+
291
+ @wraps(init)
292
+ def handle_extra_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None:
293
+ if config.extra == Extra.ignore:
294
+ init(self, *args, **{k: v for k, v in kwargs.items() if k in self.__dataclass_fields__})
295
+
296
+ elif config.extra == Extra.allow:
297
+ for k, v in kwargs.items():
298
+ # internal attributes are not valid extra fields, and should not be set from user input:
299
+ if not k.startswith('__pydantic'):
300
+ self.__dict__.setdefault(k, v)
301
+ init(self, *args, **{k: v for k, v in kwargs.items() if k in self.__dataclass_fields__})
302
+
303
+ else:
304
+ init(self, *args, **kwargs)
305
+
306
+ if hasattr(dc_cls, '__post_init__'):
307
+ try:
308
+ post_init = dc_cls.__post_init__.__wrapped__ # type: ignore[attr-defined]
309
+ except AttributeError:
310
+ post_init = dc_cls.__post_init__
311
+
312
+ @wraps(post_init)
313
+ def new_post_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None:
314
+ if config.post_init_call == 'before_validation':
315
+ post_init(self, *args, **kwargs)
316
+
317
+ if self.__class__.__pydantic_run_validation__:
318
+ self.__pydantic_validate_values__()
319
+ if hasattr(self, '__post_init_post_parse__'):
320
+ self.__post_init_post_parse__(*args, **kwargs)
321
+
322
+ if config.post_init_call == 'after_validation':
323
+ post_init(self, *args, **kwargs)
324
+
325
+ setattr(dc_cls, '__init__', handle_extra_init)
326
+ setattr(dc_cls, '__post_init__', new_post_init)
327
+
328
+ else:
329
+
330
+ @wraps(init)
331
+ def new_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None:
332
+ handle_extra_init(self, *args, **kwargs)
333
+
334
+ if self.__class__.__pydantic_run_validation__:
335
+ self.__pydantic_validate_values__()
336
+
337
+ if hasattr(self, '__post_init_post_parse__'):
338
+ # We need to find again the initvars. To do that we use `__dataclass_fields__` instead of
339
+ # public method `dataclasses.fields`
340
+
341
+ # get all initvars and their default values
342
+ initvars_and_values: Dict[str, Any] = {}
343
+ for i, f in enumerate(self.__class__.__dataclass_fields__.values()):
344
+ if f._field_type is dataclasses._FIELD_INITVAR: # type: ignore[attr-defined]
345
+ try:
346
+ # set arg value by default
347
+ initvars_and_values[f.name] = args[i]
348
+ except IndexError:
349
+ initvars_and_values[f.name] = kwargs.get(f.name, f.default)
350
+
351
+ self.__post_init_post_parse__(**initvars_and_values)
352
+
353
+ setattr(dc_cls, '__init__', new_init)
354
+
355
+ setattr(dc_cls, '__pydantic_run_validation__', ClassAttribute('__pydantic_run_validation__', validate_on_init))
356
+ setattr(dc_cls, '__pydantic_initialised__', False)
357
+ setattr(dc_cls, '__pydantic_model__', create_pydantic_model_from_dataclass(dc_cls, config, dc_cls_doc))
358
+ setattr(dc_cls, '__pydantic_validate_values__', _dataclass_validate_values)
359
+ setattr(dc_cls, '__validate__', classmethod(_validate_dataclass))
360
+ setattr(dc_cls, '__get_validators__', classmethod(_get_validators))
361
+
362
+ if dc_cls.__pydantic_model__.__config__.validate_assignment and not dc_cls.__dataclass_params__.frozen:
363
+ setattr(dc_cls, '__setattr__', _dataclass_validate_assignment_setattr)
364
+
365
+
366
+ def _get_validators(cls: 'DataclassClassOrWrapper') -> 'CallableGenerator':
367
+ yield cls.__validate__
368
+
369
+
370
+ def _validate_dataclass(cls: Type['DataclassT'], v: Any) -> 'DataclassT':
371
+ with set_validation(cls, True):
372
+ if isinstance(v, cls):
373
+ v.__pydantic_validate_values__()
374
+ return v
375
+ elif isinstance(v, (list, tuple)):
376
+ return cls(*v)
377
+ elif isinstance(v, dict):
378
+ return cls(**v)
379
+ else:
380
+ raise DataclassTypeError(class_name=cls.__name__)
381
+
382
+
383
+ def create_pydantic_model_from_dataclass(
384
+ dc_cls: Type['Dataclass'],
385
+ config: Type[Any] = BaseConfig,
386
+ dc_cls_doc: Optional[str] = None,
387
+ ) -> Type['BaseModel']:
388
+ field_definitions: Dict[str, Any] = {}
389
+ for field in dataclasses.fields(dc_cls):
390
+ default: Any = Undefined
391
+ default_factory: Optional['NoArgAnyCallable'] = None
392
+ field_info: FieldInfo
393
+
394
+ if field.default is not dataclasses.MISSING:
395
+ default = field.default
396
+ elif field.default_factory is not dataclasses.MISSING:
397
+ default_factory = field.default_factory
398
+ else:
399
+ default = Required
400
+
401
+ if isinstance(default, FieldInfo):
402
+ field_info = default
403
+ dc_cls.__pydantic_has_field_info_default__ = True
404
+ else:
405
+ field_info = Field(default=default, default_factory=default_factory, **field.metadata)
406
+
407
+ field_definitions[field.name] = (field.type, field_info)
408
+
409
+ validators = gather_all_validators(dc_cls)
410
+ model: Type['BaseModel'] = create_model(
411
+ dc_cls.__name__,
412
+ __config__=config,
413
+ __module__=dc_cls.__module__,
414
+ __validators__=validators,
415
+ __cls_kwargs__={'__resolve_forward_refs__': False},
416
+ **field_definitions,
417
+ )
418
+ model.__doc__ = dc_cls_doc if dc_cls_doc is not None else dc_cls.__doc__ or ''
419
+ return model
420
+
421
+
422
+ if sys.version_info >= (3, 8):
423
+
424
+ def _is_field_cached_property(obj: 'Dataclass', k: str) -> bool:
425
+ return isinstance(getattr(type(obj), k, None), cached_property)
426
+
427
+ else:
428
+
429
+ def _is_field_cached_property(obj: 'Dataclass', k: str) -> bool:
430
+ return False
431
+
432
+
433
+ def _dataclass_validate_values(self: 'Dataclass') -> None:
434
+ # validation errors can occur if this function is called twice on an already initialised dataclass.
435
+ # for example if Extra.forbid is enabled, it would consider __pydantic_initialised__ an invalid extra property
436
+ if getattr(self, '__pydantic_initialised__'):
437
+ return
438
+ if getattr(self, '__pydantic_has_field_info_default__', False):
439
+ # We need to remove `FieldInfo` values since they are not valid as input
440
+ # It's ok to do that because they are obviously the default values!
441
+ input_data = {
442
+ k: v
443
+ for k, v in self.__dict__.items()
444
+ if not (isinstance(v, FieldInfo) or _is_field_cached_property(self, k))
445
+ }
446
+ else:
447
+ input_data = {k: v for k, v in self.__dict__.items() if not _is_field_cached_property(self, k)}
448
+ d, _, validation_error = validate_model(self.__pydantic_model__, input_data, cls=self.__class__)
449
+ if validation_error:
450
+ raise validation_error
451
+ self.__dict__.update(d)
452
+ object.__setattr__(self, '__pydantic_initialised__', True)
453
+
454
+
455
+ def _dataclass_validate_assignment_setattr(self: 'Dataclass', name: str, value: Any) -> None:
456
+ if self.__pydantic_initialised__:
457
+ d = dict(self.__dict__)
458
+ d.pop(name, None)
459
+ known_field = self.__pydantic_model__.__fields__.get(name, None)
460
+ if known_field:
461
+ value, error_ = known_field.validate(value, d, loc=name, cls=self.__class__)
462
+ if error_:
463
+ raise ValidationError([error_], self.__class__)
464
+
465
+ object.__setattr__(self, name, value)
466
+
467
+
468
+ def is_builtin_dataclass(_cls: Type[Any]) -> bool:
469
+ """
470
+ Whether a class is a stdlib dataclass
471
+ (useful to discriminated a pydantic dataclass that is actually a wrapper around a stdlib dataclass)
472
+
473
+ we check that
474
+ - `_cls` is a dataclass
475
+ - `_cls` is not a processed pydantic dataclass (with a basemodel attached)
476
+ - `_cls` is not a pydantic dataclass inheriting directly from a stdlib dataclass
477
+ e.g.
478
+ ```
479
+ @dataclasses.dataclass
480
+ class A:
481
+ x: int
482
+
483
+ @pboot_validator.dataclasses.dataclass
484
+ class B(A):
485
+ y: int
486
+ ```
487
+ In this case, when we first check `B`, we make an extra check and look at the annotations ('y'),
488
+ which won't be a superset of all the dataclass fields (only the stdlib fields i.e. 'x')
489
+ """
490
+ return (
491
+ dataclasses.is_dataclass(_cls)
492
+ and not hasattr(_cls, '__pydantic_model__')
493
+ and set(_cls.__dataclass_fields__).issuperset(set(getattr(_cls, '__annotations__', {})))
494
+ )
495
+
496
+
497
+ def make_dataclass_validator(dc_cls: Type['Dataclass'], config: Type[BaseConfig]) -> 'CallableGenerator':
498
+ """
499
+ Create a pboot_validator.dataclass from a builtin dataclass to add type validation
500
+ and yield the validators
501
+ It retrieves the parameters of the dataclass and forwards them to the newly created dataclass
502
+ """
503
+ yield from _get_validators(dataclass(dc_cls, config=config, use_proxy=True))