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,156 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from collections.abc import Mapping, Sequence
5
+ from typing import TYPE_CHECKING, Any, TypeAlias, TypeGuard
6
+
7
+ from pydantic_core import CoreSchema, core_schema
8
+
9
+ if TYPE_CHECKING:
10
+ from rich.console import Console
11
+
12
+ AnyFunctionSchema: TypeAlias = (
13
+ core_schema.AfterValidatorFunctionSchema
14
+ | core_schema.BeforeValidatorFunctionSchema
15
+ | core_schema.WrapValidatorFunctionSchema
16
+ | core_schema.PlainValidatorFunctionSchema
17
+ )
18
+
19
+
20
+ FunctionSchemaWithInnerSchema: TypeAlias = (
21
+ core_schema.AfterValidatorFunctionSchema
22
+ | core_schema.BeforeValidatorFunctionSchema
23
+ | core_schema.WrapValidatorFunctionSchema
24
+ )
25
+
26
+
27
+ CoreSchemaField: TypeAlias = (
28
+ core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField | core_schema.ComputedField
29
+ )
30
+
31
+ CoreSchemaOrField: TypeAlias = core_schema.CoreSchema | CoreSchemaField
32
+
33
+ _CORE_SCHEMA_FIELD_TYPES = {'typed-dict-field', 'dataclass-field', 'model-field', 'computed-field'}
34
+ _FUNCTION_WITH_INNER_SCHEMA_TYPES = {'function-before', 'function-after', 'function-wrap'}
35
+ _LIST_LIKE_SCHEMA_WITH_ITEMS_TYPES = {'list', 'deque', 'set', 'frozenset'}
36
+
37
+
38
+ def is_core_schema(
39
+ schema: CoreSchemaOrField,
40
+ ) -> TypeGuard[CoreSchema]:
41
+ return schema['type'] not in _CORE_SCHEMA_FIELD_TYPES
42
+
43
+
44
+ def is_core_schema_field(
45
+ schema: CoreSchemaOrField,
46
+ ) -> TypeGuard[CoreSchemaField]:
47
+ return schema['type'] in _CORE_SCHEMA_FIELD_TYPES
48
+
49
+
50
+ def is_function_with_inner_schema(
51
+ schema: CoreSchemaOrField,
52
+ ) -> TypeGuard[FunctionSchemaWithInnerSchema]:
53
+ return schema['type'] in _FUNCTION_WITH_INNER_SCHEMA_TYPES
54
+
55
+
56
+ def as_ser_schema(schema: CoreSchema) -> core_schema.SerSchema:
57
+ """Return a schema suitable for the `'serialization'` key of a core schema, from an arbitrary core schema.
58
+
59
+ Any core schema can be used as a serialization schema, except `'function-plain'` and `'function-wrap'`
60
+ schemas, as these types are already used by the plain and wrap serializer *function* schemas.
61
+ For these, mimic what pydantic-core would do if they were used as the *main* schema:
62
+
63
+ - if the function schema has a `'serialization'` schema, use it.
64
+ - otherwise, a `'function-plain'` schema is serialized as `'any'`, and a `'function-wrap'` schema
65
+ is serialized using its inner schema.
66
+
67
+ Note that `schema` is expected to be a *core* schema (e.g. as returned by the schema generator),
68
+ not an existing `'serialization'` schema.
69
+ """
70
+ if schema['type'] == 'function-plain' or schema['type'] == 'function-wrap':
71
+ if (ser_schema := schema.get('serialization')) is not None:
72
+ return ser_schema
73
+ if schema['type'] == 'function-plain':
74
+ return core_schema.any_schema()
75
+ return as_ser_schema(schema['schema'])
76
+ return schema
77
+
78
+
79
+ def is_list_like_schema_with_items_schema(
80
+ schema: CoreSchema,
81
+ ) -> TypeGuard[core_schema.ListSchema | core_schema.SetSchema | core_schema.FrozenSetSchema]:
82
+ return schema['type'] in _LIST_LIKE_SCHEMA_WITH_ITEMS_TYPES
83
+
84
+
85
+ def get_ref(s: core_schema.CoreSchema) -> None | str:
86
+ """Get the ref from the schema if it has one.
87
+ This exists just for type checking to work correctly.
88
+ """
89
+ return s.get('ref', None)
90
+
91
+
92
+ def _clean_schema_for_pretty_print(obj: Any, strip_metadata: bool = True) -> Any: # pragma: no cover
93
+ """A utility function to remove irrelevant information from a core schema."""
94
+ if isinstance(obj, Mapping):
95
+ new_dct = {}
96
+ for k, v in obj.items():
97
+ if k == 'metadata' and strip_metadata:
98
+ new_metadata = {}
99
+
100
+ for meta_k, meta_v in v.items():
101
+ if meta_k in ('pydantic_js_functions', 'pydantic_js_annotation_functions'):
102
+ new_metadata['js_metadata'] = '<stripped>'
103
+ else:
104
+ new_metadata[meta_k] = _clean_schema_for_pretty_print(meta_v, strip_metadata=strip_metadata)
105
+
106
+ if list(new_metadata.keys()) == ['js_metadata']:
107
+ new_metadata = {'<stripped>'}
108
+
109
+ new_dct[k] = new_metadata
110
+ # Remove some defaults:
111
+ elif k in ('custom_init', 'root_model') and not v:
112
+ continue
113
+ else:
114
+ new_dct[k] = _clean_schema_for_pretty_print(v, strip_metadata=strip_metadata)
115
+
116
+ return new_dct
117
+ elif isinstance(obj, Sequence) and not isinstance(obj, str):
118
+ return [_clean_schema_for_pretty_print(v, strip_metadata=strip_metadata) for v in obj]
119
+ else:
120
+ return obj
121
+
122
+
123
+ def pretty_print_core_schema(
124
+ val: Any,
125
+ *,
126
+ console: Console | None = None,
127
+ max_depth: int | None = None,
128
+ strip_metadata: bool = True,
129
+ ) -> None: # pragma: no cover
130
+ """Pretty-print a core schema using the `rich` library.
131
+
132
+ Args:
133
+ val: The core schema to print, or a Pydantic model/dataclass/type adapter
134
+ (in which case the cached core schema is fetched and printed).
135
+ console: A rich console to use when printing. Defaults to the global rich console instance.
136
+ max_depth: The number of nesting levels which may be printed.
137
+ strip_metadata: Whether to strip metadata in the output. If `True` any known core metadata
138
+ attributes will be stripped (but custom attributes are kept). Defaults to `True`.
139
+ """
140
+ # lazy import:
141
+ from rich.pretty import pprint
142
+
143
+ # circ. imports:
144
+ from pboot_validator import BaseModel, TypeAdapter
145
+ from pboot_validator.dataclasses import is_pydantic_dataclass
146
+
147
+ if (inspect.isclass(val) and issubclass(val, BaseModel)) or is_pydantic_dataclass(val):
148
+ val = val.__pydantic_core_schema__
149
+ if isinstance(val, TypeAdapter):
150
+ val = val.core_schema
151
+ cleaned_schema = _clean_schema_for_pretty_print(val, strip_metadata=strip_metadata)
152
+
153
+ pprint(cleaned_schema, console=console, max_depth=max_depth)
154
+
155
+
156
+ pps = pretty_print_core_schema
@@ -0,0 +1,327 @@
1
+ """Private logic for creating pydantic dataclasses."""
2
+
3
+ from __future__ import annotations as _annotations
4
+
5
+ import copy
6
+ import dataclasses
7
+ import sys
8
+ import warnings
9
+ from collections.abc import Generator
10
+ from functools import partial
11
+ from typing import TYPE_CHECKING, Any, ClassVar, Protocol, TypeAlias, cast
12
+
13
+ from pydantic_core import (
14
+ ArgsKwargs,
15
+ SchemaSerializer,
16
+ SchemaValidator,
17
+ core_schema,
18
+ )
19
+ from typing_extensions import TypeIs
20
+
21
+ from ..errors import PydanticUndefinedAnnotation
22
+ from ..fields import FieldInfo
23
+ from ..plugin._schema_validator import PluggableSchemaValidator, create_schema_validator
24
+ from ..warnings import PydanticDeprecatedSince20
25
+ from . import _config, _decorators
26
+ from ._contextlib import contextmanager
27
+ from ._fields import collect_dataclass_fields
28
+ from ._generate_schema import GenerateSchema, InvalidSchemaError
29
+ from ._generics import get_standard_typevars_map
30
+ from ._mock_val_ser import set_dataclass_mocks
31
+ from ._namespace_utils import NsResolver
32
+ from ._signature import generate_pydantic_signature
33
+ from ._utils import LazyClassAttribute
34
+
35
+ if TYPE_CHECKING:
36
+ from _typeshed import DataclassInstance as StandardDataclass
37
+
38
+ from ..config import ConfigDict
39
+
40
+ class PydanticDataclass(StandardDataclass, Protocol):
41
+ """A protocol containing attributes only available once a class has been decorated as a Pydantic dataclass.
42
+
43
+ Attributes:
44
+ __pydantic_config__: Pydantic-specific configuration settings for the dataclass.
45
+ __pydantic_complete__: Whether dataclass building is completed, or if there are still undefined fields.
46
+ __pydantic_core_schema__: The pydantic-core schema used to build the SchemaValidator and SchemaSerializer.
47
+ __pydantic_decorators__: Metadata containing the decorators defined on the dataclass.
48
+ __pydantic_fields__: Metadata about the fields defined on the dataclass.
49
+ __pydantic_serializer__: The pydantic-core SchemaSerializer used to dump instances of the dataclass.
50
+ __pydantic_validator__: The pydantic-core SchemaValidator used to validate instances of the dataclass.
51
+ """
52
+
53
+ __pydantic_config__: ClassVar[ConfigDict]
54
+ __pydantic_complete__: ClassVar[bool]
55
+ __pydantic_core_schema__: ClassVar[core_schema.CoreSchema]
56
+ __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos]
57
+ __pydantic_fields__: ClassVar[dict[str, FieldInfo]]
58
+ __pydantic_serializer__: ClassVar[SchemaSerializer]
59
+ __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator]
60
+
61
+ @classmethod
62
+ def __pydantic_fields_complete__(cls) -> bool: ...
63
+
64
+
65
+ def set_dataclass_fields(
66
+ cls: type[StandardDataclass],
67
+ config_wrapper: _config.ConfigWrapper,
68
+ ns_resolver: NsResolver | None = None,
69
+ ) -> None:
70
+ """Collect and set `cls.__pydantic_fields__`.
71
+
72
+ Args:
73
+ cls: The class.
74
+ config_wrapper: The config wrapper instance.
75
+ ns_resolver: Namespace resolver to use when getting dataclass annotations.
76
+ """
77
+ typevars_map = get_standard_typevars_map(cls)
78
+ fields = collect_dataclass_fields(
79
+ cls, ns_resolver=ns_resolver, typevars_map=typevars_map, config_wrapper=config_wrapper
80
+ )
81
+
82
+ cls.__pydantic_fields__ = fields # type: ignore
83
+
84
+
85
+ def complete_dataclass(
86
+ cls: type[Any],
87
+ config_wrapper: _config.ConfigWrapper,
88
+ *,
89
+ raise_errors: bool = True,
90
+ ns_resolver: NsResolver | None = None,
91
+ _force_build: bool = False,
92
+ ) -> bool:
93
+ """Finish building a pydantic dataclass.
94
+
95
+ This logic is called on a class which has already been wrapped in `dataclasses.dataclass()`.
96
+
97
+ This is somewhat analogous to `pboot_validator._internal._model_construction.complete_model_class`.
98
+
99
+ Args:
100
+ cls: The class.
101
+ config_wrapper: The config wrapper instance.
102
+ raise_errors: Whether to raise errors, defaults to `True`.
103
+ ns_resolver: The namespace resolver instance to use when collecting dataclass fields
104
+ and during schema building.
105
+ _force_build: Whether to force building the dataclass, no matter if
106
+ [`defer_build`][pboot_validator.config.ConfigDict.defer_build] is set.
107
+
108
+ Returns:
109
+ `True` if building a pydantic dataclass is successfully completed, `False` otherwise.
110
+
111
+ Raises:
112
+ PydanticUndefinedAnnotation: If `raise_error` is `True` and there is an undefined annotations.
113
+ """
114
+ original_init = cls.__init__
115
+
116
+ # dataclass.__init__ must be defined here so its `__qualname__` can be changed since functions can't be copied,
117
+ # and so that the mock validator is used if building was deferred:
118
+ def __init__(__dataclass_self__: PydanticDataclass, *args: Any, **kwargs: Any) -> None:
119
+ __tracebackhide__ = True
120
+ s = __dataclass_self__
121
+ s.__pydantic_validator__.validate_python(ArgsKwargs(args, kwargs), self_instance=s)
122
+
123
+ __init__.__qualname__ = f'{cls.__qualname__}.__init__'
124
+
125
+ cls.__init__ = __init__ # type: ignore
126
+ cls.__pydantic_config__ = config_wrapper.config_dict # type: ignore
127
+
128
+ set_dataclass_fields(cls, config_wrapper=config_wrapper, ns_resolver=ns_resolver)
129
+
130
+ if not _force_build and config_wrapper.defer_build:
131
+ set_dataclass_mocks(cls)
132
+ return False
133
+
134
+ if hasattr(cls, '__post_init_post_parse__'):
135
+ warnings.warn(
136
+ 'Support for `__post_init_post_parse__` has been dropped, the method will not be called',
137
+ PydanticDeprecatedSince20,
138
+ )
139
+
140
+ typevars_map = get_standard_typevars_map(cls)
141
+ gen_schema = GenerateSchema(
142
+ config_wrapper,
143
+ ns_resolver=ns_resolver,
144
+ typevars_map=typevars_map,
145
+ )
146
+
147
+ # set __signature__ attr only for the class, but not for its instances
148
+ # (because instances can define `__call__`, and `inspect.signature` shouldn't
149
+ # use the `__signature__` attribute and instead generate from `__call__`).
150
+ cls.__signature__ = LazyClassAttribute(
151
+ '__signature__',
152
+ partial(
153
+ generate_pydantic_signature,
154
+ # It's important that we reference the `original_init` here,
155
+ # as it is the one synthesized by the stdlib `dataclass` module:
156
+ init=original_init,
157
+ fields=cls.__pydantic_fields__, # type: ignore
158
+ validate_by_alias=config_wrapper.validate_by_alias,
159
+ extra=config_wrapper.extra,
160
+ is_dataclass=True,
161
+ ),
162
+ )
163
+
164
+ try:
165
+ schema = gen_schema.generate_schema(cls)
166
+ except PydanticUndefinedAnnotation as e:
167
+ if raise_errors:
168
+ raise
169
+ set_dataclass_mocks(cls, f'`{e.name}`' if e.name is not None else None)
170
+ return False
171
+
172
+ core_config = config_wrapper.core_config(title=cls.__name__)
173
+
174
+ try:
175
+ schema = gen_schema.clean_schema(schema)
176
+ except InvalidSchemaError:
177
+ set_dataclass_mocks(cls)
178
+ return False
179
+
180
+ # We are about to set all the remaining required properties expected for this cast;
181
+ # __pydantic_decorators__ and __pydantic_fields__ should already be set
182
+ cls = cast('type[PydanticDataclass]', cls)
183
+
184
+ cls.__pydantic_core_schema__ = schema
185
+ cls.__pydantic_validator__ = create_schema_validator(
186
+ schema, cls, cls.__module__, cls.__qualname__, 'dataclass', core_config, config_wrapper.plugin_settings
187
+ )
188
+ cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config)
189
+ cls.__pydantic_complete__ = True
190
+ return True
191
+
192
+
193
+ def is_stdlib_dataclass(cls: type[Any], /) -> TypeIs[type[StandardDataclass]]:
194
+ """Returns `True` if the class is a stdlib dataclass and *not* a Pydantic dataclass.
195
+
196
+ Unlike the stdlib `dataclasses.is_dataclass()` function, this does *not* include subclasses
197
+ of a dataclass that are themselves not dataclasses.
198
+
199
+ Args:
200
+ cls: The class.
201
+
202
+ Returns:
203
+ `True` if the class is a stdlib dataclass, `False` otherwise.
204
+ """
205
+ return '__dataclass_fields__' in cls.__dict__ and not hasattr(cls, '__pydantic_validator__')
206
+
207
+
208
+ def as_dataclass_field(pydantic_field: FieldInfo) -> dataclasses.Field[Any]:
209
+ field_args: dict[str, Any] = {'default': pydantic_field}
210
+
211
+ # Needed because if `doc` is set, the dataclass slots will be a dict (field name -> doc) instead of a tuple:
212
+ if sys.version_info >= (3, 14) and pydantic_field.description is not None:
213
+ field_args['doc'] = pydantic_field.description
214
+
215
+ # Needed as the stdlib dataclass module processes `kw_only` in a specific way during class construction:
216
+ if pydantic_field.kw_only is not None:
217
+ field_args['kw_only'] = pydantic_field.kw_only
218
+
219
+ # Needed as the stdlib dataclass modules generates `__repr__()` during class construction:
220
+ if pydantic_field.repr is not True:
221
+ field_args['repr'] = pydantic_field.repr
222
+
223
+ # Needed as the stdlib dataclass module uses `init` during class construction (e.g. to generate `__match_args__`),
224
+ # and `dataclasses.replace()` relies on it:
225
+ if pydantic_field.init is False:
226
+ field_args['init'] = False
227
+
228
+ return dataclasses.field(**field_args)
229
+
230
+
231
+ DcFields: TypeAlias = dict[str, dataclasses.Field[Any]]
232
+
233
+
234
+ @contextmanager
235
+ def patch_base_fields(cls: type[Any]) -> Generator[None]:
236
+ """Temporarily patch the stdlib dataclasses bases of `cls` if the Pydantic `Field()` function is used.
237
+
238
+ When creating a Pydantic dataclass, it is possible to inherit from stdlib dataclasses, where
239
+ the Pydantic `Field()` function is used. To create this Pydantic dataclass, we first apply
240
+ the stdlib `@dataclass` decorator on it. During the construction of the stdlib dataclass,
241
+ the `kw_only`, `repr` and `init` field arguments need to be understood by the stdlib *during* the
242
+ dataclass construction. To do so, we temporarily patch the fields dictionary of the affected
243
+ bases.
244
+
245
+ For instance, with the following example:
246
+
247
+ ```python {test="skip" lint="skip"}
248
+ import dataclasses as stdlib_dc
249
+
250
+ import pboot_validator
251
+ import pboot_validator.dataclasses as pydantic_dc
252
+
253
+ @stdlib_dc.dataclass
254
+ class A:
255
+ a: int = pboot_validator.Field(repr=False)
256
+
257
+ # Notice that the `repr` attribute of the dataclass field is `True`:
258
+ A.__dataclass_fields__['a']
259
+ #> dataclass.Field(default=FieldInfo(repr=False), repr=True, ...)
260
+
261
+ @pydantic_dc.dataclass
262
+ class B(A):
263
+ b: int = pboot_validator.Field(repr=False)
264
+ ```
265
+
266
+ When passing `B` to the stdlib `@dataclass` decorator, it will look for fields in the parent classes
267
+ and reuse them directly. When this context manager is active, `A` will be temporarily patched to be
268
+ equivalent to:
269
+
270
+ ```python {test="skip" lint="skip"}
271
+ @stdlib_dc.dataclass
272
+ class A:
273
+ a: int = stdlib_dc.field(default=Field(repr=False), repr=False)
274
+ ```
275
+
276
+ !!! note
277
+ This is only applied to the bases of `cls`, and not `cls` itself. The reason is that the Pydantic
278
+ dataclass decorator "owns" `cls` (in the previous example, `B`). As such, we instead modify the fields
279
+ directly (in the previous example, we simply do `setattr(B, 'b', as_dataclass_field(pydantic_field))`).
280
+
281
+ !!! note
282
+ This approach is far from ideal, and can probably be the source of unwanted side effects/race conditions.
283
+ The previous implemented approach was mutating the `__annotations__` dict of `cls`, which is no longer a
284
+ safe operation in Python 3.14+, and resulted in unexpected behavior with field ordering anyway.
285
+ """
286
+ # A list of two-tuples, the first element being a reference to the
287
+ # dataclass fields dictionary, the second element being a mapping between
288
+ # the field names that were modified, and their original `Field`:
289
+ original_fields_list: list[tuple[DcFields, DcFields]] = []
290
+
291
+ for base in cls.__mro__[1:]:
292
+ dc_fields: dict[str, dataclasses.Field[Any]] = base.__dict__.get('__dataclass_fields__', {})
293
+ dc_fields_with_pydantic_field_defaults = {
294
+ field_name: field
295
+ for field_name, field in dc_fields.items()
296
+ if isinstance(field.default, FieldInfo)
297
+ # Only do the patching if one of the affected attributes is set:
298
+ and (
299
+ field.default.description is not None
300
+ or field.default.kw_only is not None
301
+ or field.default.repr is not True
302
+ or field.default.init is False
303
+ )
304
+ }
305
+ if dc_fields_with_pydantic_field_defaults:
306
+ original_fields_list.append((dc_fields, dc_fields_with_pydantic_field_defaults))
307
+ for field_name, field in dc_fields_with_pydantic_field_defaults.items():
308
+ default = cast(FieldInfo, field.default)
309
+ # `dataclasses.Field` isn't documented as working with `copy.copy()`.
310
+ # It is a class with `__slots__`, so should work (and we hope for the best):
311
+ new_dc_field = copy.copy(field)
312
+ # For base fields, no need to set `doc` from `FieldInfo.description`, this is only relevant
313
+ # for the class under construction and handled in `as_dataclass_field()`.
314
+ if default.kw_only is not None:
315
+ new_dc_field.kw_only = default.kw_only
316
+ if default.repr is not True:
317
+ new_dc_field.repr = default.repr
318
+ if default.init is False:
319
+ new_dc_field.init = False
320
+ dc_fields[field_name] = new_dc_field
321
+
322
+ try:
323
+ yield
324
+ finally:
325
+ for fields, original_fields in original_fields_list:
326
+ for field_name, original_field in original_fields.items():
327
+ fields[field_name] = original_field