Coverage for pydantic / _internal / _fields.py: 98.49%
343 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
1"""Private logic related to fields (the `Field()` function and `FieldInfo` class), and arguments to `Annotated`."""
3from __future__ import annotations as _annotations 1glmabcpqrhijsknodef
5import dataclasses 1glmabcpqrhijsknodef
6import warnings 1glmabcpqrhijsknodef
7from collections.abc import Callable, Mapping 1glmabcpqrhijsknodef
8from functools import cache 1glmabcpqrhijsknodef
9from inspect import Parameter, ismethoddescriptor 1glmabcpqrhijsknodef
10from re import Pattern 1glmabcpqrhijsknodef
11from typing import TYPE_CHECKING, Any, TypeVar, cast 1glmabcpqrhijsknodef
13from pydantic_core import PydanticUndefined 1glmabcpqrhijsknodef
14from typing_extensions import TypeForm, TypeIs, get_args, get_origin # noqa: UP035 (for `get_args` and `get_origin`) 1glmabcpqrhijsknodef
15from typing_inspection import typing_objects 1glmabcpqrhijsknodef
16from typing_inspection.introspection import AnnotationSource 1glmabcpqrhijsknodef
18from pydantic.errors import PydanticUserError 1glmabcpqrhijsknodef
20from ..aliases import AliasGenerator 1glmabcpqrhijsknodef
21from . import _generics, _typing_extra 1glmabcpqrhijsknodef
22from ._config import ConfigWrapper 1glmabcpqrhijsknodef
23from ._docs_extraction import extract_docstrings_from_cls 1glmabcpqrhijsknodef
24from ._import_utils import import_cached_base_model, import_cached_field_info 1glmabcpqrhijsknodef
25from ._namespace_utils import NsResolver 1glmabcpqrhijsknodef
26from ._repr import Representation 1glmabcpqrhijsknodef
27from ._utils import can_be_positional, get_first_not_none, smart_deepcopy 1glmabcpqrhijsknodef
29if TYPE_CHECKING: 1glmabcpqrhijsknodef
30 from annotated_types import BaseMetadata
32 from ..fields import FieldInfo, ModelPrivateAttr
33 from ..main import BaseModel
34 from ._dataclasses import PydanticDataclass, StandardDataclass
35 from ._decorators import DecoratorInfos
38class PydanticMetadata(Representation): 1glmabcpqrhijsknodef
39 """Base class for annotation markers like `Strict`."""
41 __slots__ = () 1glmabcpqrhijsknodef
44@dataclasses.dataclass(slots=True, kw_only=True) 1glmabcpqrhijsknodef
45class PydanticExtraInfo: 1glmabcpqrhijsknodef
46 annotation: TypeForm[Any] 1glmabcpqrhijsknodef
47 complete: bool 1glmabcpqrhijsknodef
50@dataclasses.dataclass(slots=True, kw_only=True) 1glmabcpqrhijsknodef
51class ModelNamespaceInfo: 1glmabcpqrhijsknodef
52 """Information gathered by inspecting the namespace of a model class before it is created.
54 Decisions requiring the (possibly unevaluatable at class creation time) annotations (such as
55 whether a sunder-named attribute is a private attribute or a class variable) are deferred to
56 `collect_model_fields()`, where evaluated annotations are available.
57 """
59 private_attributes: dict[str, ModelPrivateAttr] 1glmabcpqrhijsknodef
60 """Private attributes explicitly assigned a `ModelPrivateAttr` instance (removed from the namespace).""" 1glmabcpqrhijsknodef
62 ignored_names: set[str] 1glmabcpqrhijsknodef
63 """Names of the namespace attributes with a value of an ignored type.""" 1glmabcpqrhijsknodef
65 ignored_types: tuple[type[Any], ...] 1glmabcpqrhijsknodef
66 """The ignored types (the `ignored_types` config value, together with the implicitly ignored types).""" 1glmabcpqrhijsknodef
68 private_candidates: list[str] 1glmabcpqrhijsknodef
69 """Sunder-named attributes assigned in the namespace, to be converted to private attributes 1glmabcpqrhijsknodef
70 unless annotated as class variables."""
72 field_candidates: list[str] 1glmabcpqrhijsknodef
73 """Namespace attributes with a valid field name, required to have a type annotation.""" 1glmabcpqrhijsknodef
75 base_field_names: set[str] 1glmabcpqrhijsknodef
76 """The field names of the model's bases.""" 1glmabcpqrhijsknodef
78 model_config_assigned: bool 1glmabcpqrhijsknodef
79 """Whether `model_config` was assigned a value in the namespace.""" 1glmabcpqrhijsknodef
82def pydantic_general_metadata(**metadata: Any) -> BaseMetadata: 1glmabcpqrhijsknodef
83 """Create a new `_PydanticGeneralMetadata` class with the given metadata.
85 Args:
86 **metadata: The metadata to add.
88 Returns:
89 The new `_PydanticGeneralMetadata` class.
90 """
91 return _general_metadata_cls()(metadata) # type: ignore 1glmabcpqrhijknodef
94@cache 1glmabcpqrhijsknodef
95def _general_metadata_cls() -> type[BaseMetadata]: 1glmabcpqrhijsknodef
96 """Do it this way to avoid importing `annotated_types` at import time."""
97 from annotated_types import BaseMetadata 1glmabcpqrhijknodef
99 class _PydanticGeneralMetadata(PydanticMetadata, BaseMetadata): 1glmabcpqrhijknodef
100 """Pydantic general metadata like `max_digits`."""
102 def __init__(self, metadata: Any): 1glmabcpqrhijknodef
103 self.__dict__ = metadata 1glmabcpqrhijknodef
105 return _PydanticGeneralMetadata # type: ignore 1glmabcpqrhijknodef
108def _check_protected_namespaces( 1glmabcpqrhijsknodef
109 protected_namespaces: tuple[str | Pattern[str], ...],
110 ann_name: str,
111 bases: tuple[type[Any], ...],
112 cls_name: str,
113) -> None:
114 BaseModel = import_cached_base_model() 1glmabcpqrhijsknodef
116 for protected_namespace in protected_namespaces: 1glmabcpqrhijsknodef
117 ns_violation = False 1glmabcpqrhijsknodef
118 if isinstance(protected_namespace, Pattern): 1glmabcpqrhijsknodef
119 ns_violation = protected_namespace.match(ann_name) is not None 1glmabcpqrhijknodef
120 elif isinstance(protected_namespace, str): 120 ↛ 123line 120 didn't jump to line 123 because the condition on line 120 was always true1glmabcpqrhijsknodef
121 ns_violation = ann_name.startswith(protected_namespace) 1glmabcpqrhijsknodef
123 if ns_violation: 1glmabcpqrhijsknodef
124 for b in bases: 1glmabcpqrhijknodef
125 if hasattr(b, ann_name): 1glmabcpqrhijknodef
126 if not (issubclass(b, BaseModel) and ann_name in getattr(b, '__pydantic_fields__', {})): 126 ↛ 124line 126 didn't jump to line 124 because the condition on line 126 was always true1glmabcknodef
127 raise ValueError( 1glmabcknodef
128 f'Field {ann_name!r} conflicts with member {getattr(b, ann_name)}'
129 f' of protected namespace {protected_namespace!r}.'
130 )
131 else:
132 valid_namespaces: list[str] = [] 1glmabcpqrhijknodef
133 for pn in protected_namespaces: 1glmabcpqrhijknodef
134 if isinstance(pn, Pattern): 1glmabcpqrhijknodef
135 if not pn.match(ann_name): 1glmabcpqrhijknodef
136 valid_namespaces.append(f're.compile({pn.pattern!r})') 1glmabcpqrhijknodef
137 else:
138 if not ann_name.startswith(pn): 1glmabcpqrhijknodef
139 valid_namespaces.append(f"'{pn}'") 1glmabcpqrhijknodef
141 valid_namespaces_str = f'({", ".join(valid_namespaces)}{",)" if len(valid_namespaces) == 1 else ")"}' 1glmabcpqrhijknodef
143 warnings.warn( 1glmabcpqrhijknodef
144 f'Field {ann_name!r} in {cls_name!r} conflicts with protected namespace {protected_namespace!r}.\n\n'
145 f"You may be able to solve this by setting the 'protected_namespaces' configuration to {valid_namespaces_str}.",
146 UserWarning,
147 stacklevel=5,
148 )
151def _update_fields_from_docstrings(cls: type[Any], fields: dict[str, FieldInfo], use_inspect: bool = False) -> None: 1glmabcpqrhijsknodef
152 fields_docs = extract_docstrings_from_cls(cls, use_inspect=use_inspect) 1glmabcpqrhijknodef
153 for ann_name, field_info in fields.items(): 1glmabcpqrhijknodef
154 if field_info.description is None and ann_name in fields_docs: 1glmabcpqrhijknodef
155 field_info.description = fields_docs[ann_name] 1glmabcpqrhijknodef
158def _apply_field_title_generator_to_field_info( 1glmabcpqrhijsknodef
159 title_generator: Callable[[str, FieldInfo], str],
160 field_name: str,
161 field_info: FieldInfo,
162):
163 if field_info.title is None: 1glmabcpqrhijknodef
164 title = title_generator(field_name, field_info) 1glmabcpqrhijknodef
165 if not isinstance(title, str): 1glmabcpqrhijknodef
166 raise TypeError(f'field_title_generator {title_generator} must return str, not {title.__class__}') 1glmabcpqrhijknodef
168 field_info.title = title 1glmabcpqrhijknodef
171def _apply_alias_generator_to_field_info( 1glmabcpqrhijsknodef
172 alias_generator: Callable[[str], str] | AliasGenerator, field_name: str, field_info: FieldInfo
173):
174 """Apply an alias generator to aliases on a `FieldInfo` instance if appropriate.
176 Args:
177 alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance.
178 field_name: The name of the field from which to generate the alias.
179 field_info: The `FieldInfo` instance to which the alias generator is (maybe) applied.
180 """
181 # Apply an alias_generator if
182 # 1. An alias is not specified
183 # 2. An alias is specified, but the priority is <= 1
184 if ( 1abchijdef
185 field_info.alias_priority is None
186 or field_info.alias_priority <= 1
187 or field_info.alias is None
188 or field_info.validation_alias is None
189 or field_info.serialization_alias is None
190 ):
191 alias, validation_alias, serialization_alias = None, None, None 1glmabcpqrhijknodef
193 if isinstance(alias_generator, AliasGenerator): 1glmabcpqrhijknodef
194 alias, validation_alias, serialization_alias = alias_generator.generate_aliases(field_name) 1glmabcpqrhijknodef
195 elif callable(alias_generator): 195 ↛ 203line 195 didn't jump to line 203 because the condition on line 195 was always true1glmabcpqrhijknodef
196 alias = alias_generator(field_name) 1glmabcpqrhijknodef
197 if not isinstance(alias, str): 1glmabcpqrhijknodef
198 raise TypeError(f'alias_generator {alias_generator} must return str, not {alias.__class__}') 1glmabcpqrhijknodef
200 # if priority is not set, we set to 1
201 # which supports the case where the alias_generator from a child class is used
202 # to generate an alias for a field in a parent class
203 if field_info.alias_priority is None or field_info.alias_priority <= 1: 1glmabcpqrhijknodef
204 field_info.alias_priority = 1 1glmabcpqrhijknodef
206 # if the priority is 1, then we set the aliases to the generated alias
207 if field_info.alias_priority == 1: 1glmabcpqrhijknodef
208 field_info.serialization_alias = get_first_not_none(serialization_alias, alias) 1glmabcpqrhijknodef
209 field_info.validation_alias = get_first_not_none(validation_alias, alias) 1glmabcpqrhijknodef
210 field_info.alias = alias 1glmabcpqrhijknodef
212 # if any of the aliases are not set, then we set them to the corresponding generated alias
213 if field_info.alias is None: 1glmabcpqrhijknodef
214 field_info.alias = alias 1glmabcpqrhijknodef
215 if field_info.serialization_alias is None: 1glmabcpqrhijknodef
216 field_info.serialization_alias = get_first_not_none(serialization_alias, alias) 1glmabcpqrhijknodef
217 if field_info.validation_alias is None: 1glmabcpqrhijknodef
218 field_info.validation_alias = get_first_not_none(validation_alias, alias) 1glmabcpqrhijknodef
221def update_field_from_config(config_wrapper: ConfigWrapper, field_name: str, field_info: FieldInfo) -> None: 1glmabcpqrhijsknodef
222 """Update the `FieldInfo` instance from the configuration set on the model it belongs to.
224 This will apply the title and alias generators from the configuration.
226 Args:
227 config_wrapper: The configuration from the model.
228 field_name: The field name the `FieldInfo` instance is attached to.
229 field_info: The `FieldInfo` instance to update.
230 """
231 field_title_generator = field_info.field_title_generator or config_wrapper.field_title_generator 1glmabcpqrhijsknodef
232 if field_title_generator is not None: 1glmabcpqrhijsknodef
233 _apply_field_title_generator_to_field_info(field_title_generator, field_name, field_info) 1glmabcpqrhijknodef
234 if config_wrapper.alias_generator is not None: 1glmabcpqrhijsknodef
235 _apply_alias_generator_to_field_info(config_wrapper.alias_generator, field_name, field_info) 1glmabcpqrhijknodef
238def collect_model_fields( # noqa: C901 1glmabcpqrhijsknodef
239 cls: type[BaseModel],
240 config_wrapper: ConfigWrapper,
241 ns_resolver: NsResolver,
242 *,
243 typevars_map: Mapping[TypeVar, Any] | None = None,
244 namespace_info: ModelNamespaceInfo | None = None,
245) -> tuple[dict[str, FieldInfo], PydanticExtraInfo | None, set[str], dict[str, ModelPrivateAttr]]:
246 """Collect the fields, class variables names and private attributes of a nascent Pydantic model.
248 The fields collection process is *lenient*, meaning it won't error if string annotations
249 fail to evaluate. If this happens, the original annotation (and assigned value, if any)
250 is stored on the created `FieldInfo` instance.
252 The `rebuild_model_fields()` should be called at a later point (e.g. when rebuilding the model),
253 and will make use of these stored attributes.
255 Args:
256 cls: BaseModel or dataclass.
257 config_wrapper: The config wrapper instance.
258 ns_resolver: Namespace resolver to use when getting model annotations.
259 typevars_map: A dictionary mapping type variables to their concrete types.
260 namespace_info: The result of inspecting the class namespace before the class was created.
262 Returns:
263 A four-tuple containing the model fields, the `PydanticExtraInfo` instance if the `__pydantic_extra__` annotation is set,
264 the class variables names, and the private attributes discovered from the namespace and annotations.
266 Raises:
267 NameError: If there is a conflict between a field name and protected namespaces.
268 PydanticUserError: If there is a field other than `root` in `RootModel`, or if one of
269 the namespace checks performed with `namespace_info` fails.
270 """
271 FieldInfo_ = import_cached_field_info() 1glmabcpqrhijsknodef
273 from ..fields import ModelPrivateAttr, PrivateAttr 1glmabcpqrhijsknodef
275 bases = cls.__bases__ 1glmabcpqrhijsknodef
276 parent_fields_lookup: dict[str, FieldInfo] = {} 1glmabcpqrhijsknodef
277 for base in reversed(bases): 1glmabcpqrhijsknodef
278 if model_fields := getattr(base, '__pydantic_fields__', None): 1glmabcpqrhijsknodef
279 parent_fields_lookup.update(model_fields) 1glmabcpqrhijsknodef
281 type_hints = _typing_extra.get_model_type_hints(cls, ns_resolver=ns_resolver) 1glmabcpqrhijsknodef
283 # `cls_annotations` is only used to determine if an annotation comes from a parent class
284 cls_annotations = _typing_extra.safe_get_annotations(cls) 1glmabcpqrhijsknodef
286 private_attributes: dict[str, ModelPrivateAttr] = {} 1glmabcpqrhijsknodef
288 if namespace_info is not None: 288 ↛ 328line 288 didn't jump to line 328 because the condition on line 288 was always true1glmabcpqrhijsknodef
289 if 'model_config' in cls_annotations and not namespace_info.model_config_assigned: 1glmabcpqrhijsknodef
290 raise PydanticUserError( 1glmabcpqrhijknodef
291 '`model_config` cannot be used as a model field name. Use `model_config` for model configuration.',
292 code='model-config-invalid-field-name',
293 )
295 for var_name in namespace_info.private_candidates: 1glmabcpqrhijsknodef
296 # A sunder-named attribute with an assigned value is a private attribute,
297 # unless annotated as a class variable:
298 hint = type_hints.get(var_name) 1glmabcpqrhijknodef
299 if hint is None or not _typing_extra.is_classvar_annotation(hint[0]): 1glmabcpqrhijknodef
300 # Unlike for the annotation-only private attributes below, `__set_name__()` must not be
301 # called on the wrapping `PrivateAttr()` here: the assigned value stayed in the namespace
302 # during class creation, so `type.__new__()` already invoked the protocol on it natively:
303 private_attributes[var_name] = cast('ModelPrivateAttr', PrivateAttr(default=cls.__dict__[var_name])) 1glmabcpqrhijknodef
304 delattr(cls, var_name) 1glmabcpqrhijknodef
306 for var_name in namespace_info.field_candidates: 1glmabcpqrhijsknodef
307 if var_name in cls_annotations: 1glmabcpqrhijsknodef
308 continue 1glmabcpqrhijsknodef
309 if var_name in namespace_info.base_field_names: 1glmabcpqrhijknodef
310 raise PydanticUserError( 1glmabcpqrhijknodef
311 f'Field {var_name!r} defined on a base class was overridden by a non-annotated attribute. '
312 f'All field definitions, including overrides, require a type annotation.',
313 code='model-field-overridden',
314 )
315 value = cls.__dict__[var_name] 1glmabcpqrhijknodef
316 if isinstance(value, FieldInfo_): 1glmabcpqrhijknodef
317 raise PydanticUserError( 1glmabcpqrhijknodef
318 f'Field {var_name!r} requires a type annotation', code='model-field-missing-annotation'
319 )
320 else:
321 raise PydanticUserError( 1glmabcpqrhijknodef
322 f'A non-annotated attribute was detected: `{var_name} = {value!r}`. All model fields require a '
323 f'type annotation; if `{var_name}` is not meant to be a field, you may be able to resolve this '
324 f"error by annotating it as a `ClassVar` or updating `model_config['ignored_types']`.",
325 code='model-field-missing-annotation',
326 )
328 fields: dict[str, FieldInfo] = {} 1glmabcpqrhijsknodef
330 class_vars: set[str] = set() 1glmabcpqrhijsknodef
331 for ann_name, (ann_type, evaluated) in type_hints.items(): 1glmabcpqrhijsknodef
332 if ann_name == 'model_config': 1glmabcpqrhijsknodef
333 # We never want to treat `model_config` as a field
334 # Note: we may need to change this logic if/when we introduce a `BareModel` class with no
335 # protected namespaces (where `model_config` might be allowed as a field name)
336 continue 1glmabcpqrhijknodef
338 _check_protected_namespaces( 1glmabcpqrhijsknodef
339 protected_namespaces=config_wrapper.protected_namespaces,
340 ann_name=ann_name,
341 bases=bases,
342 cls_name=cls.__name__,
343 )
345 if _typing_extra.is_classvar_annotation(ann_type): 1glmabcpqrhijsknodef
346 class_vars.add(ann_name) 1glmabcpqrhijsknodef
347 continue 1glmabcpqrhijsknodef
349 if not is_valid_field_name(ann_name): 1glmabcpqrhijsknodef
350 if ( 1abchijdef
351 namespace_info is not None
352 and is_valid_privateattr_name(ann_name)
353 and ann_name in cls_annotations
354 and ann_name not in private_attributes
355 and ann_name not in namespace_info.private_attributes
356 and ann_name not in namespace_info.ignored_names
357 and ann_type not in namespace_info.ignored_types
358 and getattr(ann_type, '__module__', None) != 'functools'
359 ):
360 # A sunder-named annotation (with no assigned value, as this case is handled above)
361 # defines a private attribute:
362 private_attr: ModelPrivateAttr | None = None 1glmabcpqrhijknodef
363 if typing_objects.is_annotated(get_origin(ann_type)): 1glmabcpqrhijknodef
364 _, *metadata = get_args(ann_type) 1glmabcpqrhijknodef
365 private_attr = next((v for v in metadata if isinstance(v, ModelPrivateAttr)), None) 1glmabcpqrhijknodef
366 if private_attr is None: 1glmabcpqrhijknodef
367 private_attr = cast('ModelPrivateAttr', PrivateAttr()) 1glmabcpqrhijknodef
368 private_attr.__set_name__(cls, ann_name) 1glmabcpqrhijknodef
369 private_attributes[ann_name] = private_attr 1glmabcpqrhijknodef
370 continue 1glmabcpqrhijknodef
372 assigned_value = getattr(cls, ann_name, PydanticUndefined) 1glmabcpqrhijsknodef
374 if cls.__pydantic_root_model__ and ann_name != 'root': 1glmabcpqrhijsknodef
375 raise PydanticUserError( 1glmabcpqrhijknodef
376 f"Unexpected field with name {ann_name!r}; only 'root' is allowed as a field of a `RootModel`",
377 code=None,
378 )
380 for base in bases: 1glmabcpqrhijsknodef
381 if hasattr(base, ann_name): 1glmabcpqrhijsknodef
382 if ann_name not in cls_annotations: 1glmabcpqrhijknodef
383 # Don't warn when a field exists in a parent class but has not been defined in the current class
384 continue 1glmabcpqrhijknodef
386 # when building a generic model with `MyModel[int]`, the generic_origin check makes sure we don't get
387 # "... shadows an attribute" warnings
388 generic_origin = getattr(cls, '__pydantic_generic_metadata__', {}).get('origin') 1glmabcpqrhijknodef
389 if base is generic_origin: 389 ↛ 391line 389 didn't jump to line 391 because the condition on line 389 was never true1glmabcpqrhijknodef
390 # Don't warn when "shadowing" of attributes in parametrized generics
391 continue
393 dataclass_fields = { 1glmabcpqrhijknodef
394 field.name for field in (dataclasses.fields(base) if dataclasses.is_dataclass(base) else ())
395 }
396 if ann_name in dataclass_fields: 1glmabcpqrhijknodef
397 # Don't warn when inheriting stdlib dataclasses whose fields are "shadowed" by defaults being set
398 # on the class instance.
399 continue 1glmabcpqrhijknodef
401 warnings.warn( 1glmabcpqrhijknodef
402 f'Field name "{ann_name}" in "{cls.__qualname__}" shadows an attribute in parent '
403 f'"{base.__qualname__}"',
404 UserWarning,
405 stacklevel=4,
406 )
408 if assigned_value is PydanticUndefined: # no assignment, just a plain annotation 1glmabcpqrhijsknodef
409 if ann_name in cls_annotations or ann_name not in parent_fields_lookup: 1glmabcpqrhijsknodef
410 # field is either:
411 # - present in the current model's annotations (and *not* from parent classes)
412 # - not found on any base classes; this seems to be caused by fields not getting
413 # generated due to models not being fully defined while initializing recursive models.
414 # Nothing stops us from just creating a `FieldInfo` for this type hint, so we do this.
415 field_info = FieldInfo_.from_annotation(ann_type, _source=AnnotationSource.CLASS) 1glmabcpqrhijsknodef
416 field_info._original_annotation = ann_type 1glmabcpqrhijsknodef
417 if not evaluated: 1glmabcpqrhijsknodef
418 field_info._complete = False 1glmabcpqrhijsknodef
419 # Store the original annotation that should be used to rebuild
420 # the field info later:
421 else:
422 # The field was present on one of the (possibly multiple) base classes, we make a copy directly from it.
423 parent_field_info = parent_fields_lookup[ann_name]._copy() 1glmabcpqrhijsknodef
425 # The only case where substituting the type variables is relevant (i.e. when `typevars_map` is not empty)
426 # is when a generic class is parameterized (e.g. `MyGenericModel[int, str]`), which creates a new class object
427 # (unlike the stdlib genercis that create a generic alias). In this case, we are guaranteed to only have to copy
428 # from the origin/parent model (e.g. `MyGenericModel`).
429 if typevars_map: 1glmabcpqrhijsknodef
430 field_info = _recreate_field_info( 1glmabcpqrhijsknodef
431 parent_field_info, ns_resolver=ns_resolver, typevars_map=typevars_map, lenient=True
432 )
433 else:
434 field_info = parent_field_info 1glmabcpqrhijsknodef
436 else: # An assigned value is present (either the default value, or a `Field()` function)
437 if isinstance(assigned_value, FieldInfo_) and ismethoddescriptor(assigned_value.default): 1glmabcpqrhijsknodef
438 # `assigned_value` was fetched using `getattr`, which triggers a call to `__get__`
439 # for descriptors, so we do the same if the `= field(default=...)` form is used.
440 # Note that we only do this for method descriptors for now, we might want to
441 # extend this to any descriptor in the future (by simply checking for
442 # `hasattr(assigned_value.default, '__get__')`).
443 default = assigned_value.default.__get__(None, cls) 1glmabcpqrhijknodef
444 assigned_value.default = default 1glmabcpqrhijknodef
445 assigned_value._attributes_set['default'] = default 1glmabcpqrhijknodef
447 field_info = FieldInfo_.from_annotated_attribute(ann_type, assigned_value, _source=AnnotationSource.CLASS) 1glmabcpqrhijsknodef
449 # Store the original annotation and assignment value that could be used to rebuild the field info later.
450 field_info._original_assignment = assigned_value 1glmabcpqrhijsknodef
451 field_info._original_annotation = ann_type 1glmabcpqrhijsknodef
452 if not evaluated: 1glmabcpqrhijsknodef
453 field_info._complete = False 1glmabcpqrhijknodef
455 # attributes which are fields are removed from the class namespace:
456 # 1. To match the behaviour of annotation-only fields
457 # 2. To avoid false positives in the NameError check above
458 try: 1glmabcpqrhijsknodef
459 delattr(cls, ann_name) 1glmabcpqrhijsknodef
460 except AttributeError: 1glmabcpqrhijknodef
461 pass # indicates the attribute was on a parent class 1glmabcpqrhijknodef
463 # Use cls.__dict__['__pydantic_decorators__'] instead of cls.__pydantic_decorators__
464 # to make sure the decorators have already been built for this exact class
465 decorators: DecoratorInfos = cls.__dict__['__pydantic_decorators__'] 1glmabcpqrhijsknodef
466 if ann_name in decorators.computed_fields: 1glmabcpqrhijsknodef
467 raise TypeError( 1glmabcpqrhijknodef
468 f'Field {ann_name!r} of class {cls.__name__!r} overrides symbol of same name in a parent class. '
469 'This override with a computed_field is incompatible.'
470 )
471 fields[ann_name] = field_info 1glmabcpqrhijsknodef
473 if field_info._complete: 1glmabcpqrhijsknodef
474 # If not complete, this will be called in `rebuild_model_fields()`:
475 update_field_from_config(config_wrapper, ann_name, field_info) 1glmabcpqrhijsknodef
477 if config_wrapper.use_attribute_docstrings: 1glmabcpqrhijsknodef
478 _update_fields_from_docstrings(cls, fields) 1glmabcpqrhijknodef
480 pydantic_extra_info: PydanticExtraInfo | None = None 1glmabcpqrhijsknodef
481 if '__pydantic_extra__' in type_hints: 1glmabcpqrhijsknodef
482 parent_extra_info: PydanticExtraInfo | None = None 1glmabcpqrhijknodef
483 if '__pydantic_extra__' not in cls_annotations: 1glmabcpqrhijknodef
484 # The annotation is only present on parent classes. As with fields, we make use of the parent's
485 # extra info, where type variables are already substituted:
486 for base in bases: 486 ↛ 491line 486 didn't jump to line 491 because the loop on line 486 didn't complete1glmabcpqrhijknodef
487 parent_extra_info = getattr(base, '__pydantic_extra_info__', None) 1glmabcpqrhijknodef
488 if parent_extra_info is not None: 488 ↛ 486line 488 didn't jump to line 486 because the condition on line 488 was always true1glmabcpqrhijknodef
489 break 1glmabcpqrhijknodef
491 if parent_extra_info is not None: 1glmabcpqrhijknodef
492 # As with fields, the only case where substituting the type variables is relevant (i.e. when
493 # `typevars_map` is not empty) is when a generic class is parameterized:
494 if typevars_map and parent_extra_info.complete: 1glmabcpqrhijknodef
495 # If not complete, `rebuild_model_fields()` takes care of it:
496 pydantic_extra_info = PydanticExtraInfo( 1glmabcpqrhijknodef
497 annotation=_generics.replace_types(parent_extra_info.annotation, typevars_map),
498 complete=True,
499 )
500 else:
501 pydantic_extra_info = parent_extra_info 1glmabcpqrhijknodef
502 else:
503 ann, complete = type_hints['__pydantic_extra__'] 1glmabcpqrhijknodef
504 if complete: 1glmabcpqrhijknodef
505 # If not complete, `rebuild_model_fields()` takes care of it:
506 ann = _generics.replace_types(ann, typevars_map) 1glmabcpqrhijknodef
507 pydantic_extra_info = PydanticExtraInfo( 1glmabcpqrhijknodef
508 annotation=ann,
509 complete=complete,
510 )
512 return fields, pydantic_extra_info, class_vars, private_attributes 1glmabcpqrhijsknodef
515def rebuild_model_fields( 1glmabcpqrhijsknodef
516 cls: type[BaseModel],
517 *,
518 config_wrapper: ConfigWrapper,
519 ns_resolver: NsResolver,
520 typevars_map: Mapping[TypeVar, Any],
521) -> tuple[dict[str, FieldInfo], PydanticExtraInfo | None]:
522 """Rebuild the (already present) model fields by trying to reevaluate annotations.
524 This function should be called whenever a model with incomplete fields is encountered.
526 Returns:
527 A two-tuple, the first element being the rebuilt fields, the second element being
528 the rebuild `PydanticExtraInfo` instance, if available.
530 Raises:
531 NameError: If one of the annotations failed to evaluate.
533 Note:
534 This function *doesn't* mutate the model fields in place, as it can be called during
535 schema generation, where you don't want to mutate other model's fields.
536 """
537 rebuilt_fields: dict[str, FieldInfo] = {} 1glmabcpqrhijsknodef
538 origin = cls.__pydantic_generic_metadata__['origin'] 1glmabcpqrhijsknodef
539 with ns_resolver.push(cls): 1glmabcpqrhijsknodef
540 for f_name, field_info in cls.__pydantic_fields__.items(): 1glmabcpqrhijsknodef
541 if field_info._complete: 1glmabcpqrhijsknodef
542 rebuilt_fields[f_name] = field_info 1glmabcpqrhijsknodef
543 else:
544 annotation = field_info._original_annotation 1glmabcpqrhijsknodef
545 if origin is not None and (origin_field := origin.__pydantic_fields__.get(f_name)) is not None: 1glmabcpqrhijsknodef
546 # For parametrized generic models, the stored annotation can mix names from the origin class
547 # and (forward) type arguments, which need to be evaluated in different namespaces. For instance:
548 #
549 # class Model[T](BaseModel):
550 # a: dict[T, 'Later']
551 #
552 # M = Model['Item']
553 #
554 # The stored annotation of `M.a` is `dict['Item', 'Later']`, where `'Later'` must be evaluated
555 # in the namespace of `Model` and `'Item'` in the namespace of `M`. Instead,
556 # first evaluate the (unsubstituted) annotation of the origin in its own namespace:
557 with ns_resolver.push(origin): 1glmabcpqrhijknodef
558 annotation = _typing_extra.eval_type( 1glmabcpqrhijknodef
559 origin_field._original_annotation,
560 *ns_resolver.types_namespace,
561 )
562 new_field = _recreate_field_info( 1glmabcpqrhijsknodef
563 field_info,
564 ns_resolver=ns_resolver,
565 typevars_map=typevars_map,
566 lenient=False,
567 annotation=annotation,
568 )
569 update_field_from_config(config_wrapper, f_name, new_field) 1glmabcpqrhijsknodef
570 rebuilt_fields[f_name] = new_field 1glmabcpqrhijsknodef
572 if cls.__pydantic_extra_info__ is not None and not cls.__pydantic_extra_info__.complete: 1glmabcpqrhijsknodef
573 # Not the best pattern (see comment in `_recreate_field_info()`):
574 ann = _typing_extra.eval_type( 1glmabcpqrhijknodef
575 cls.__pydantic_extra_info__.annotation,
576 *ns_resolver.types_namespace,
577 )
578 ann = _generics.replace_types(ann, typevars_map) 1glmabcpqrhijknodef
579 ann = _typing_extra.eval_type( 1glmabcpqrhijknodef
580 ann,
581 *ns_resolver.types_namespace,
582 )
583 rebuilt_extra_info = PydanticExtraInfo( 1glmabcpqrhijknodef
584 annotation=ann,
585 complete=True,
586 )
587 else:
588 rebuilt_extra_info = cls.__pydantic_extra_info__ 1glmabcpqrhijsknodef
590 return rebuilt_fields, rebuilt_extra_info 1glmabcpqrhijsknodef
593def _recreate_field_info( 1glmabcpqrhijsknodef
594 field_info: FieldInfo,
595 ns_resolver: NsResolver,
596 typevars_map: Mapping[TypeVar, Any],
597 *,
598 lenient: bool,
599 annotation: Any = PydanticUndefined,
600) -> FieldInfo:
601 FieldInfo_ = import_cached_field_info() 1glmabcpqrhijsknodef
603 if annotation is PydanticUndefined: 1glmabcpqrhijsknodef
604 annotation = field_info._original_annotation 1glmabcpqrhijsknodef
606 existing_desc = field_info.description 1glmabcpqrhijsknodef
607 if lenient: 1glmabcpqrhijsknodef
608 ann = _generics.replace_types(field_info._original_annotation, typevars_map) 1glmabcpqrhijsknodef
609 ann, evaluated = _typing_extra.try_eval_type( 1glmabcpqrhijsknodef
610 ann,
611 *ns_resolver.types_namespace,
612 )
613 else:
614 # Not the best pattern, maybe we could ship our own `eval_type()`,
615 # that would replace the type variables on the fly during evaluation.
616 ann = _typing_extra.eval_type( 1glmabcpqrhijsknodef
617 annotation,
618 *ns_resolver.types_namespace,
619 )
620 ann = _generics.replace_types(ann, typevars_map) 1glmabcpqrhijsknodef
621 ann = _typing_extra.eval_type( 1glmabcpqrhijsknodef
622 ann,
623 *ns_resolver.types_namespace,
624 )
625 evaluated = True 1glmabcpqrhijsknodef
627 if (assign := field_info._original_assignment) is PydanticUndefined: 1glmabcpqrhijsknodef
628 new_field = FieldInfo_.from_annotation(ann, _source=AnnotationSource.CLASS) 1glmabcpqrhijsknodef
629 else:
630 new_field = FieldInfo_.from_annotated_attribute(ann, assign, _source=AnnotationSource.CLASS) 1glmabcpqrhijknodef
631 new_field._original_assignment = assign 1glmabcpqrhijknodef
632 new_field._original_annotation = ann 1glmabcpqrhijsknodef
633 # The description might come from the docstring if `use_attribute_docstrings` was `True`:
634 new_field.description = new_field.description if new_field.description is not None else existing_desc 1glmabcpqrhijsknodef
635 if not evaluated: 1glmabcpqrhijsknodef
636 new_field._complete = False 1glmabcpqrhijknodef
638 return new_field 1glmabcpqrhijsknodef
641def collect_dataclass_fields( 1glmabcpqrhijsknodef
642 cls: type[StandardDataclass],
643 *,
644 config_wrapper: ConfigWrapper,
645 ns_resolver: NsResolver | None = None,
646 typevars_map: dict[Any, Any] | None = None,
647) -> dict[str, FieldInfo]:
648 """Collect the fields of a dataclass.
650 Args:
651 cls: dataclass.
652 config_wrapper: The config wrapper instance.
653 ns_resolver: Namespace resolver to use when getting dataclass annotations.
654 Defaults to an empty instance.
655 typevars_map: A dictionary mapping type variables to their concrete types.
657 Returns:
658 The dataclass fields.
659 """
660 FieldInfo_ = import_cached_field_info() 1glmabcpqrhijsknodef
662 fields: dict[str, FieldInfo] = {} 1glmabcpqrhijsknodef
663 ns_resolver = ns_resolver or NsResolver() 1glmabcpqrhijsknodef
664 dataclass_fields = cls.__dataclass_fields__ 1glmabcpqrhijsknodef
666 # The logic here is similar to `_typing_extra.get_cls_type_hints`,
667 # although we do it manually as stdlib dataclasses already have annotations
668 # collected in each class:
669 for base in reversed(cls.__mro__): 1glmabcpqrhijsknodef
670 if not dataclasses.is_dataclass(base): 1glmabcpqrhijsknodef
671 continue 1glmabcpqrhijsknodef
673 with ns_resolver.push(base): 1glmabcpqrhijsknodef
674 for ann_name, dataclass_field in dataclass_fields.items(): 1glmabcpqrhijsknodef
675 base_anns = _typing_extra.safe_get_annotations(base) 1glmabcpqrhijsknodef
677 if ann_name not in base_anns: 1glmabcpqrhijsknodef
678 # `__dataclass_fields__`contains every field, even the ones from base classes.
679 # Only collect the ones defined on `base`.
680 continue 1glmabcpqrhijknodef
682 globalns, localns = ns_resolver.types_namespace 1glmabcpqrhijsknodef
683 ann_type, evaluated = _typing_extra.try_eval_type(dataclass_field.type, globalns, localns) 1glmabcpqrhijsknodef
685 if _typing_extra.is_classvar_annotation(ann_type): 1glmabcpqrhijsknodef
686 continue 1glmabcpqrhijknodef
688 if ( 1gabcphijkdef
689 not dataclass_field.init
690 and dataclass_field.default is dataclasses.MISSING
691 and dataclass_field.default_factory is dataclasses.MISSING
692 ):
693 # TODO: We should probably do something with this so that validate_assignment behaves properly
694 # Issue: https://github.com/pydantic/pydantic/issues/5470
695 continue 1glmabcpqrhijknodef
697 if isinstance(dataclass_field.default, FieldInfo_): 1glmabcpqrhijsknodef
698 if dataclass_field.default.init_var: 1glmabcpqrhijknodef
699 if dataclass_field.default.init is False: 1glmabcpqrhijknodef
700 raise PydanticUserError( 1glmabcpqrhijknodef
701 f'Dataclass field {ann_name} has init=False and init_var=True, but these are mutually exclusive.',
702 code='clashing-init-and-init-var',
703 )
705 # TODO: same note as above re validate_assignment
706 continue 1glmabcpqrhijknodef
707 field_info = FieldInfo_.from_annotated_attribute( 1glmabcpqrhijknodef
708 ann_type, dataclass_field.default, _source=AnnotationSource.DATACLASS
709 )
710 field_info._original_assignment = dataclass_field.default 1glmabcpqrhijknodef
711 else:
712 field_info = FieldInfo_.from_annotated_attribute( 1glmabcpqrhijsknodef
713 ann_type, dataclass_field, _source=AnnotationSource.DATACLASS
714 )
715 field_info._original_assignment = dataclass_field 1glmabcpqrhijsknodef
717 if not evaluated: 1glmabcpqrhijsknodef
718 field_info._complete = False 1glmabcpqrhijknodef
719 field_info._original_annotation = ann_type 1glmabcpqrhijknodef
721 fields[ann_name] = field_info 1glmabcpqrhijsknodef
722 update_field_from_config(config_wrapper, ann_name, field_info) 1glmabcpqrhijsknodef
724 if field_info.default is not PydanticUndefined and isinstance( 1glmabcpqrhijsknodef
725 getattr(cls, ann_name, field_info), FieldInfo_
726 ):
727 # We need this to fix the default when the "default" from __dataclass_fields__ is a pydantic.FieldInfo
728 setattr(cls, ann_name, field_info.default) 1glmabcpqrhijknodef
730 if typevars_map: 1glmabcpqrhijsknodef
731 for field in fields.values(): 1glmabcpqrhijknodef
732 # We don't pass any ns, as `field.annotation`
733 # was already evaluated. TODO: is this method relevant?
734 # Can't we juste use `_generics.replace_types`?
735 field.apply_typevars_map(typevars_map) 1glmabcpqrhijknodef
737 if config_wrapper.use_attribute_docstrings: 1glmabcpqrhijsknodef
738 _update_fields_from_docstrings( 1glmabcpqrhijknodef
739 cls,
740 fields,
741 # We can't rely on the (more reliable) frame inspection method
742 # for stdlib dataclasses:
743 use_inspect=not hasattr(cls, '__is_pydantic_dataclass__'),
744 )
746 return fields 1glmabcpqrhijsknodef
749def rebuild_dataclass_fields( 1glmabcpqrhijsknodef
750 cls: type[PydanticDataclass],
751 *,
752 config_wrapper: ConfigWrapper,
753 ns_resolver: NsResolver,
754 typevars_map: Mapping[TypeVar, Any],
755) -> dict[str, FieldInfo]:
756 """Rebuild the (already present) dataclass fields by trying to reevaluate annotations.
758 This function should be called whenever a dataclass with incomplete fields is encountered.
760 Raises:
761 NameError: If one of the annotations failed to evaluate.
763 Note:
764 This function *doesn't* mutate the dataclass fields in place, as it can be called during
765 schema generation, where you don't want to mutate other dataclass's fields.
766 """
767 FieldInfo_ = import_cached_field_info() 1glmabcpqrhijknodef
769 rebuilt_fields: dict[str, FieldInfo] = {} 1glmabcpqrhijknodef
770 with ns_resolver.push(cls): 1glmabcpqrhijknodef
771 for f_name, field_info in cls.__pydantic_fields__.items(): 1glmabcpqrhijknodef
772 if field_info._complete: 1glmabcpqrhijknodef
773 rebuilt_fields[f_name] = field_info 1glmabcpqrhijknodef
774 else:
775 existing_desc = field_info.description 1glmabcpqrhijknodef
776 ann = _typing_extra.eval_type( 1glmabcpqrhijknodef
777 field_info._original_annotation,
778 *ns_resolver.types_namespace,
779 )
780 ann = _generics.replace_types(ann, typevars_map) 1glmabcpqrhijknodef
781 new_field = FieldInfo_.from_annotated_attribute( 1glmabcpqrhijknodef
782 ann,
783 field_info._original_assignment,
784 _source=AnnotationSource.DATACLASS,
785 )
787 # The description might come from the docstring if `use_attribute_docstrings` was `True`:
788 new_field.description = new_field.description if new_field.description is not None else existing_desc 1glmabcpqrhijknodef
789 update_field_from_config(config_wrapper, f_name, new_field) 1glmabcpqrhijknodef
790 rebuilt_fields[f_name] = new_field 1glmabcpqrhijknodef
792 return rebuilt_fields 1glmabcpqrhijknodef
795def is_valid_field_name(name: str) -> bool: 1glmabcpqrhijsknodef
796 return not name.startswith('_') 1glmabcpqrhijsknodef
799def is_valid_privateattr_name(name: str) -> bool: 1glmabcpqrhijsknodef
800 return name.startswith('_') and not name.startswith('__') 1glmabcpqrhijsknodef
803def takes_validated_data_argument( 1glmabcpqrhijsknodef
804 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any],
805) -> TypeIs[Callable[[dict[str, Any]], Any]]:
806 """Whether the provided default factory callable has a validated data parameter."""
807 try: 1glmabcpqrhijsknodef
808 sig = _typing_extra.signature_no_eval(default_factory) 1glmabcpqrhijsknodef
809 except (ValueError, TypeError): 1glmabcpqrhijknodef
810 # `inspect.signature` might not be able to infer a signature, e.g. with C objects.
811 # In this case, we assume no data argument is present:
812 return False 1glmabcpqrhijknodef
814 parameters = list(sig.parameters.values()) 1glmabcpqrhijsknodef
816 return len(parameters) == 1 and can_be_positional(parameters[0]) and parameters[0].default is Parameter.empty 1glmabcpqrhijsknodef
819def resolve_default_value( 1glmabcpqrhijsknodef
820 *,
821 default: Any,
822 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None,
823 default_factory_takes_validated_data_argument: bool | None,
824 validated_data: dict[str, Any] | None = None,
825 call_default_factory: bool = False,
826) -> Any:
827 """Resolve the default value using either a static default or a default_factory."""
828 if default_factory is None: 1glmabcpqrhijknodef
829 return smart_deepcopy(default) 1glmabcpqrhijknodef
830 if call_default_factory: 1glmabcpqrhijknodef
831 if default_factory_takes_validated_data_argument: 1glmabcpqrhijknodef
832 fac = cast('Callable[[dict[str, Any]], Any]', default_factory) 1glmabcpqrhijknodef
833 if validated_data is None: 1glmabcpqrhijknodef
834 raise ValueError( 1glmabcpqrhijknodef
835 "The default factory requires the 'validated_data' argument, which was not provided when calling 'get_default()'."
836 )
837 return fac(validated_data) 1glmabcpqrhijknodef
838 else:
839 fac = cast('Callable[[], Any]', default_factory) 1glmabcpqrhijknodef
840 return fac() 1glmabcpqrhijknodef
842 return PydanticUndefined 1glmabcpqrhijknodef