Coverage for pydantic / fields.py: 98.12%
553 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"""Defining fields on models."""
3from __future__ import annotations as _annotations 1pdaghiqebjklsrfcmno
5import dataclasses 1pdaghiqebjklsrfcmno
6import inspect 1pdaghiqebjklsrfcmno
7import re 1pdaghiqebjklsrfcmno
8import sys 1pdaghiqebjklsrfcmno
9from collections.abc import Callable, Mapping 1pdaghiqebjklsrfcmno
10from copy import copy 1pdaghiqebjklsrfcmno
11from dataclasses import Field as DataclassField 1pdaghiqebjklsrfcmno
12from functools import cached_property 1pdaghiqebjklsrfcmno
13from types import EllipsisType 1pdaghiqebjklsrfcmno
14from typing import TYPE_CHECKING, Annotated, Any, ClassVar, Literal, TypeAlias, TypeVar, final, overload 1pdaghiqebjklsrfcmno
15from warnings import warn 1pdaghiqebjklsrfcmno
17import annotated_types 1pdaghiqebjklsrfcmno
18from pydantic_core import MISSING, PydanticUndefined 1pdaghiqebjklsrfcmno
19from typing_extensions import ( # noqa: UP035 (for `get_origin`) 1pdaghiqebjklsrfcmno
20 Self,
21 TypedDict,
22 TypeForm,
23 Unpack,
24 deprecated,
25 get_origin,
26)
27from typing_inspection import typing_objects 1pdaghiqebjklsrfcmno
28from typing_inspection.introspection import ( 1pdaghiqebjklsrfcmno
29 UNKNOWN,
30 AnnotationSource,
31 ForbiddenQualifier,
32 Qualifier,
33 inspect_annotation,
34 is_union_origin,
35)
37from . import types 1pdaghiqebjklsrfcmno
38from ._internal import _decorators, _fields, _generics, _repr, _typing_extra, _utils 1pdaghiqebjklsrfcmno
39from ._internal._namespace_utils import GlobalsNamespace, MappingNamespace 1pdaghiqebjklsrfcmno
40from .aliases import AliasChoices, AliasGenerator, AliasPath 1pdaghiqebjklsrfcmno
41from .config import JsonDict 1pdaghiqebjklsrfcmno
42from .errors import PydanticForbiddenQualifier, PydanticUserError 1pdaghiqebjklsrfcmno
44if TYPE_CHECKING: 1pdaghiqebjklsrfcmno
45 from ._internal._config import ConfigWrapper
46 from ._internal._repr import ReprArgs
49__all__ = 'Field', 'FieldInfo', 'PrivateAttr', 'computed_field' 1pdaghiqebjklsrfcmno
52_Unset: Any = PydanticUndefined 1pdaghiqebjklsrfcmno
54if sys.version_info >= (3, 13): 1pdaghiqebjklsrfcmno
55 import warnings 1aghibjklscmno
57 Deprecated: TypeAlias = warnings.deprecated | deprecated 1aghibjklscmno
58else:
59 Deprecated: TypeAlias = deprecated 1pdqerf
62class _FromFieldInfoInputs(TypedDict, total=False): 1pdaghiqebjklsrfcmno
63 """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.from_field`."""
65 annotation: TypeForm[Any] 1pdaghiqebjklsrfcmno
66 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None 1pdaghiqebjklsrfcmno
67 alias: str | None 1pdaghiqebjklsrfcmno
68 alias_priority: int | None 1pdaghiqebjklsrfcmno
69 validation_alias: str | AliasPath | AliasChoices | None 1pdaghiqebjklsrfcmno
70 serialization_alias: str | None 1pdaghiqebjklsrfcmno
71 title: str | None 1pdaghiqebjklsrfcmno
72 field_title_generator: Callable[[str, FieldInfo], str] | None 1pdaghiqebjklsrfcmno
73 description: str | None 1pdaghiqebjklsrfcmno
74 examples: list[Any] | None 1pdaghiqebjklsrfcmno
75 exclude: bool | None 1pdaghiqebjklsrfcmno
76 exclude_if: Callable[[Any], bool] | None 1pdaghiqebjklsrfcmno
77 gt: annotated_types.SupportsGt | None 1pdaghiqebjklsrfcmno
78 ge: annotated_types.SupportsGe | None 1pdaghiqebjklsrfcmno
79 lt: annotated_types.SupportsLt | None 1pdaghiqebjklsrfcmno
80 le: annotated_types.SupportsLe | None 1pdaghiqebjklsrfcmno
81 multiple_of: float | None 1pdaghiqebjklsrfcmno
82 strict: bool | None 1pdaghiqebjklsrfcmno
83 min_length: int | None 1pdaghiqebjklsrfcmno
84 max_length: int | None 1pdaghiqebjklsrfcmno
85 pattern: str | re.Pattern[str] | None 1pdaghiqebjklsrfcmno
86 allow_inf_nan: bool | None 1pdaghiqebjklsrfcmno
87 max_digits: int | None 1pdaghiqebjklsrfcmno
88 decimal_places: int | None 1pdaghiqebjklsrfcmno
89 union_mode: Literal['smart', 'left_to_right'] | None 1pdaghiqebjklsrfcmno
90 discriminator: str | types.Discriminator | None 1pdaghiqebjklsrfcmno
91 deprecated: Deprecated | str | bool | None 1pdaghiqebjklsrfcmno
92 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1pdaghiqebjklsrfcmno
93 frozen: bool | None 1pdaghiqebjklsrfcmno
94 validate_default: bool | None 1pdaghiqebjklsrfcmno
95 repr: bool 1pdaghiqebjklsrfcmno
96 init: bool | None 1pdaghiqebjklsrfcmno
97 init_var: bool | None 1pdaghiqebjklsrfcmno
98 kw_only: bool | None 1pdaghiqebjklsrfcmno
99 coerce_numbers_to_str: bool | None 1pdaghiqebjklsrfcmno
100 fail_fast: bool | None 1pdaghiqebjklsrfcmno
103class _FieldInfoAsDict(TypedDict, closed=True): 1pdaghiqebjklsrfcmno
104 annotation: TypeForm[Any] | None 1pdaghiqebjklsrfcmno
105 metadata: list[Any] 1pdaghiqebjklsrfcmno
106 attributes: dict[str, Any] 1pdaghiqebjklsrfcmno
109@final 1pdaghiqebjklsrfcmno
110class FieldInfo(_repr.Representation): 1pdaghiqebjklsrfcmno
111 """This class holds information about a field.
113 `FieldInfo` is used for any field definition regardless of whether the [`Field()`][pydantic.fields.Field]
114 function is explicitly used.
116 !!! warning
117 The `FieldInfo` class is meant to expose information about a field in a Pydantic model or dataclass.
118 `FieldInfo` instances shouldn't be instantiated directly, nor mutated.
120 If you need to derive a new model from another one and are willing to alter `FieldInfo` instances,
121 refer to this [dynamic model example](../examples/dynamic_models.md).
123 Attributes:
124 annotation: The type annotation of the field.
125 default: The default value of the field.
126 default_factory: A callable to generate the default value. The callable can either take 0 arguments
127 (in which case it is called as is) or a single argument containing the already validated data.
128 alias: The alias name of the field.
129 alias_priority: The priority of the field's alias.
130 validation_alias: The validation alias of the field.
131 serialization_alias: The serialization alias of the field.
132 title: The title of the field.
133 field_title_generator: A callable that takes a field's name and info and returns title for it.
134 description: The description of the field.
135 examples: List of examples of the field.
136 exclude: Whether to exclude the field from the model serialization.
137 exclude_if: A callable that determines whether to exclude a field during serialization based on its value.
138 discriminator: Field name or Discriminator for discriminating the type in a tagged union.
139 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
140 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
141 json_schema_extra: A dict or callable to provide extra JSON schema properties.
142 frozen: Whether the field is frozen.
143 validate_default: Whether to validate the default value of the field.
144 repr: Whether to include the field in representation of the model.
145 init: Whether the field should be included in the constructor of the dataclass.
146 init_var: Whether the field should _only_ be included in the constructor of the dataclass, and not stored.
147 kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
148 metadata: The metadata list. Contains all the data that isn't expressed as direct `FieldInfo` attributes, including:
150 * Type-specific constraints, such as `gt` or `min_length` (these are converted to metadata classes such as `annotated_types.Gt`).
151 * Any other arbitrary object used within [`Annotated`][typing.Annotated] metadata
152 (e.g. [custom types handlers](../concepts/types.md#as-an-annotation) or any object not recognized by Pydantic).
153 """
155 annotation: TypeForm[Any] | None 1pdaghiqebjklsrfcmno
156 default: Any 1pdaghiqebjklsrfcmno
157 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None 1pdaghiqebjklsrfcmno
158 alias: str | None 1pdaghiqebjklsrfcmno
159 alias_priority: int | None 1pdaghiqebjklsrfcmno
160 validation_alias: str | AliasPath | AliasChoices | None 1pdaghiqebjklsrfcmno
161 serialization_alias: str | None 1pdaghiqebjklsrfcmno
162 title: str | None 1pdaghiqebjklsrfcmno
163 field_title_generator: Callable[[str, FieldInfo], str] | None 1pdaghiqebjklsrfcmno
164 description: str | None 1pdaghiqebjklsrfcmno
165 examples: list[Any] | None 1pdaghiqebjklsrfcmno
166 exclude: bool | None 1pdaghiqebjklsrfcmno
167 exclude_if: Callable[[Any], bool] | None 1pdaghiqebjklsrfcmno
168 discriminator: str | types.Discriminator | None 1pdaghiqebjklsrfcmno
169 deprecated: Deprecated | str | bool | None 1pdaghiqebjklsrfcmno
170 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1pdaghiqebjklsrfcmno
171 frozen: bool | None 1pdaghiqebjklsrfcmno
172 validate_default: bool | None 1pdaghiqebjklsrfcmno
173 repr: bool 1pdaghiqebjklsrfcmno
174 init: bool | None 1pdaghiqebjklsrfcmno
175 init_var: bool | None 1pdaghiqebjklsrfcmno
176 kw_only: bool | None 1pdaghiqebjklsrfcmno
177 metadata: list[Any] 1pdaghiqebjklsrfcmno
179 __slots__ = ( 1pdaghiqebjklsrfcmno
180 'annotation',
181 'default',
182 'default_factory',
183 'alias',
184 'alias_priority',
185 'validation_alias',
186 'serialization_alias',
187 'title',
188 'field_title_generator',
189 'description',
190 'examples',
191 'exclude',
192 'exclude_if',
193 'discriminator',
194 'deprecated',
195 'json_schema_extra',
196 'frozen',
197 'validate_default',
198 'repr',
199 'init',
200 'init_var',
201 'kw_only',
202 'metadata',
203 '_attributes_set',
204 '_qualifiers',
205 '_complete',
206 '_original_assignment',
207 '_original_annotation',
208 '_final',
209 )
211 # used to convert kwargs to metadata/constraints,
212 # None has a special meaning - these items are collected into a `PydanticGeneralMetadata`
213 metadata_lookup: ClassVar[dict[str, Callable[[Any], Any] | None]] = { 1pdaghiqebjklsrfcmno
214 'strict': types.Strict,
215 'gt': annotated_types.Gt,
216 'ge': annotated_types.Ge,
217 'lt': annotated_types.Lt,
218 'le': annotated_types.Le,
219 'multiple_of': annotated_types.MultipleOf,
220 'min_length': annotated_types.MinLen,
221 'max_length': annotated_types.MaxLen,
222 'pattern': None,
223 'allow_inf_nan': types.AllowInfNan,
224 'max_digits': None,
225 'decimal_places': None,
226 'union_mode': None,
227 'coerce_numbers_to_str': None,
228 'fail_fast': types.FailFast,
229 }
231 def __init__( 1pdaghiqebjklsrfcmno
232 self,
233 *,
234 annotation: TypeForm[Any] | None = _Unset,
235 default: Any = _Unset,
236 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = _Unset,
237 alias: str | None = _Unset,
238 alias_priority: int | None = _Unset,
239 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
240 serialization_alias: str | None = _Unset,
241 title: str | None = _Unset,
242 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
243 description: str | None = _Unset,
244 examples: list[Any] | None = _Unset,
245 exclude: bool | None = _Unset,
246 exclude_if: Callable[[Any], bool] | None = _Unset,
247 discriminator: str | types.Discriminator | None = _Unset,
248 deprecated: Deprecated | str | bool | None = _Unset,
249 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
250 frozen: bool | None = _Unset,
251 validate_default: bool | None = _Unset,
252 repr: bool = _Unset,
253 init: bool | None = _Unset,
254 init_var: bool | None = _Unset,
255 kw_only: bool | None = _Unset,
256 # The following arguments are converted to metadata (see `_collect_metadata()`), in the order `Field()` forwards them:
257 pattern: str | re.Pattern[str] | None = _Unset,
258 coerce_numbers_to_str: bool | None = _Unset,
259 strict: bool | None = _Unset,
260 gt: annotated_types.SupportsGt | None = _Unset,
261 ge: annotated_types.SupportsGe | None = _Unset,
262 lt: annotated_types.SupportsLt | None = _Unset,
263 le: annotated_types.SupportsLe | None = _Unset,
264 multiple_of: float | None = _Unset,
265 min_length: int | None = _Unset,
266 max_length: int | None = _Unset,
267 allow_inf_nan: bool | None = _Unset,
268 max_digits: int | None = _Unset,
269 decimal_places: int | None = _Unset,
270 union_mode: Literal['smart', 'left_to_right'] | None = _Unset,
271 fail_fast: bool | None = _Unset,
272 **kwargs: Any,
273 ) -> None:
274 """This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
275 or one of the constructor classmethods.
277 See the signature of `pydantic.fields.Field` for more details about the expected arguments.
278 Unknown keyword arguments are accepted (and ignored) for backwards compatibility.
279 """
280 # Tracking the explicitly set attributes is necessary to correctly merge `Field()` functions
281 # (e.g. with `Annotated[int, Field(alias='a'), Field(alias=None)]`, even though `None` is the default value,
282 # we need to track that `alias=None` was explicitly set):
283 self._attributes_set = attributes_set = {} 1pdaghiqebjklsrfcmno
285 if annotation is _Unset: 1pdaghiqebjklsrfcmno
286 annotation = None 1pdaghiqebjklsrfcmno
287 else:
288 attributes_set['annotation'] = annotation 1pdaghiqebjklsrfcmno
289 self.annotation = annotation 1pdaghiqebjklsrfcmno
291 if default is _Unset or default is Ellipsis: 1pdaghiqebjklsrfcmno
292 default = PydanticUndefined 1pdaghiqebjklsrfcmno
293 else:
294 attributes_set['default'] = default 1pdaghiqebjklsrfcmno
295 self.default = default 1pdaghiqebjklsrfcmno
297 if default_factory is _Unset: 1pdaghiqebjklsrfcmno
298 default_factory = None 1pdaghiqebjklsrfcmno
299 else:
300 attributes_set['default_factory'] = default_factory 1pdaghiqebjklsrfcmno
301 self.default_factory = default_factory 1pdaghiqebjklsrfcmno
303 if default is not PydanticUndefined and default_factory is not None: 1pdaghiqebjklsrfcmno
304 raise TypeError('cannot specify both default and default_factory') 1pdaghiqebjklrfcmno
306 if alias is _Unset: 1pdaghiqebjklsrfcmno
307 alias = None 1pdaghiqebjklsrfcmno
308 else:
309 attributes_set['alias'] = alias 1pdaghiqebjklsrfcmno
310 self.alias = alias 1pdaghiqebjklsrfcmno
312 if alias_priority is _Unset: 1pdaghiqebjklsrfcmno
313 alias_priority = None 1pdaghiqebjklsrfcmno
314 else:
315 attributes_set['alias_priority'] = alias_priority 1pdaghiqebjklrfcmno
317 if validation_alias is _Unset: 1pdaghiqebjklsrfcmno
318 validation_alias = None 1pdaghiqebjklsrfcmno
319 else:
320 attributes_set['validation_alias'] = validation_alias 1pdaghiqebjklsrfcmno
321 self.validation_alias = validation_alias 1pdaghiqebjklsrfcmno
323 if serialization_alias is _Unset: 1pdaghiqebjklsrfcmno
324 serialization_alias = None 1pdaghiqebjklsrfcmno
325 else:
326 attributes_set['serialization_alias'] = serialization_alias 1pdaghiqebjklsrfcmno
327 self.serialization_alias = serialization_alias 1pdaghiqebjklsrfcmno
329 alias_is_set = alias is not None or validation_alias is not None or serialization_alias is not None 1pdaghiqebjklsrfcmno
330 self.alias_priority = (alias_priority or 2) if alias_is_set else None 1pdaghiqebjklsrfcmno
332 if title is _Unset: 1pdaghiqebjklsrfcmno
333 title = None 1pdaghiqebjklsrfcmno
334 else:
335 attributes_set['title'] = title 1pdaghiqebjklrfcmno
336 self.title = title 1pdaghiqebjklsrfcmno
338 if field_title_generator is _Unset: 1pdaghiqebjklsrfcmno
339 field_title_generator = None 1pdaghiqebjklsrfcmno
340 else:
341 attributes_set['field_title_generator'] = field_title_generator 1pdaghiqebjklrfcmno
342 self.field_title_generator = field_title_generator 1pdaghiqebjklsrfcmno
344 if description is _Unset: 1pdaghiqebjklsrfcmno
345 description = None 1pdaghiqebjklsrfcmno
346 else:
347 attributes_set['description'] = description 1pdaghiqebjklrfcmno
348 self.description = description 1pdaghiqebjklsrfcmno
350 if examples is _Unset: 1pdaghiqebjklsrfcmno
351 examples = None 1pdaghiqebjklsrfcmno
352 else:
353 attributes_set['examples'] = examples 1pdaghiqebjklrfcmno
354 self.examples = examples 1pdaghiqebjklsrfcmno
356 if exclude is _Unset: 1pdaghiqebjklsrfcmno
357 exclude = None 1pdaghiqebjklsrfcmno
358 else:
359 attributes_set['exclude'] = exclude 1pdaghiqebjklrfcmno
360 self.exclude = exclude 1pdaghiqebjklsrfcmno
362 if exclude_if is _Unset: 1pdaghiqebjklsrfcmno
363 exclude_if = None 1pdaghiqebjklsrfcmno
364 else:
365 attributes_set['exclude_if'] = exclude_if 1pdaghiqebjklrfcmno
366 self.exclude_if = exclude_if 1pdaghiqebjklsrfcmno
368 if discriminator is _Unset: 1pdaghiqebjklsrfcmno
369 discriminator = None 1pdaghiqebjklsrfcmno
370 else:
371 attributes_set['discriminator'] = discriminator 1pdaghiqebjklrfcmno
372 self.discriminator = discriminator 1pdaghiqebjklsrfcmno
374 if deprecated is _Unset: 1pdaghiqebjklsrfcmno
375 # For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden
376 deprecated = getattr(self, 'deprecated', None) 1pdaghiqebjklsrfcmno
377 else:
378 attributes_set['deprecated'] = deprecated 1pdaghiqebjklrfcmno
379 self.deprecated = deprecated 1pdaghiqebjklsrfcmno
381 if repr is _Unset: 1pdaghiqebjklsrfcmno
382 repr = True 1pdaghiqebjklsrfcmno
383 else:
384 attributes_set['repr'] = repr 1pdaghiqebjklsrfcmno
385 self.repr = repr 1pdaghiqebjklsrfcmno
387 if json_schema_extra is _Unset: 1pdaghiqebjklsrfcmno
388 json_schema_extra = None 1pdaghiqebjklsrfcmno
389 else:
390 attributes_set['json_schema_extra'] = json_schema_extra 1pdaghiqebjklrfcmno
391 self.json_schema_extra = json_schema_extra 1pdaghiqebjklsrfcmno
393 if validate_default is _Unset: 1pdaghiqebjklsrfcmno
394 validate_default = None 1pdaghiqebjklsrfcmno
395 else:
396 attributes_set['validate_default'] = validate_default 1pdaghiqebjklrfcmno
397 self.validate_default = validate_default 1pdaghiqebjklsrfcmno
399 if frozen is _Unset: 1pdaghiqebjklsrfcmno
400 frozen = None 1pdaghiqebjklsrfcmno
401 else:
402 attributes_set['frozen'] = frozen 1pdaghiqebjklrfcmno
403 self.frozen = frozen 1pdaghiqebjklsrfcmno
405 # currently only used on dataclasses
406 if init is _Unset: 1pdaghiqebjklsrfcmno
407 init = None 1pdaghiqebjklsrfcmno
408 else:
409 attributes_set['init'] = init 1pdaghiqebjklsrfcmno
410 self.init = init 1pdaghiqebjklsrfcmno
412 if init_var is _Unset: 1pdaghiqebjklsrfcmno
413 init_var = None 1pdaghiqebjklsrfcmno
414 else:
415 attributes_set['init_var'] = init_var 1pdaghiqebjklsrfcmno
416 self.init_var = init_var 1pdaghiqebjklsrfcmno
418 if kw_only is _Unset: 1pdaghiqebjklsrfcmno
419 kw_only = None 1pdaghiqebjklsrfcmno
420 else:
421 attributes_set['kw_only'] = kw_only 1pdaghiqebjklsrfcmno
422 self.kw_only = kw_only 1pdaghiqebjklsrfcmno
424 # (in the order `Field()` forwards them, which determines the order of the metadata)
425 metadata_kwargs: dict[str, Any] = {} 1pdaghiqebjklsrfcmno
426 if pattern is not _Unset: 1pdaghiqebjklsrfcmno
427 metadata_kwargs['pattern'] = pattern 1pdaghiqebjklrfcmno
428 if coerce_numbers_to_str is not _Unset: 1pdaghiqebjklsrfcmno
429 metadata_kwargs['coerce_numbers_to_str'] = coerce_numbers_to_str 1pdaghiqebjklrfcmno
430 if strict is not _Unset: 1pdaghiqebjklsrfcmno
431 metadata_kwargs['strict'] = strict 1pdaghiqebjklrfcmno
432 if gt is not _Unset: 1pdaghiqebjklsrfcmno
433 metadata_kwargs['gt'] = gt 1pdaghiqebjklrfcmno
434 if ge is not _Unset: 1pdaghiqebjklsrfcmno
435 metadata_kwargs['ge'] = ge 1pdaghiqebjklrfcmno
436 if lt is not _Unset: 1pdaghiqebjklsrfcmno
437 metadata_kwargs['lt'] = lt 1pdaghiqebjklrfcmno
438 if le is not _Unset: 1pdaghiqebjklsrfcmno
439 metadata_kwargs['le'] = le 1pdaghiqebjklrfcmno
440 if multiple_of is not _Unset: 1pdaghiqebjklsrfcmno
441 metadata_kwargs['multiple_of'] = multiple_of 1pdaghiqebjklrfcmno
442 if min_length is not _Unset: 1pdaghiqebjklsrfcmno
443 metadata_kwargs['min_length'] = min_length 1pdaghiqebjklrfcmno
444 if max_length is not _Unset: 1pdaghiqebjklsrfcmno
445 metadata_kwargs['max_length'] = max_length 1pdaghiqebjklrfcmno
446 if allow_inf_nan is not _Unset: 1pdaghiqebjklsrfcmno
447 metadata_kwargs['allow_inf_nan'] = allow_inf_nan 1pdaghiqebjklrfcmno
448 if max_digits is not _Unset: 1pdaghiqebjklsrfcmno
449 metadata_kwargs['max_digits'] = max_digits 1pdaghiqebjklrfcmno
450 if decimal_places is not _Unset: 1pdaghiqebjklsrfcmno
451 metadata_kwargs['decimal_places'] = decimal_places 1pdaghiqebjklrfcmno
452 if union_mode is not _Unset: 1pdaghiqebjklsrfcmno
453 metadata_kwargs['union_mode'] = union_mode 1pdaghiqebjklrfcmno
454 if fail_fast is not _Unset: 1pdaghiqebjklsrfcmno
455 metadata_kwargs['fail_fast'] = fail_fast 1pdaghiqebjklrfcmno
456 self.metadata = self._collect_metadata(metadata_kwargs) if metadata_kwargs else [] 1pdaghiqebjklsrfcmno
458 if kwargs: 458 ↛ 460line 458 didn't jump to line 460 because the condition on line 458 was never true1pdaghiqebjklsrfcmno
459 # Unknown keyword arguments (kept for backwards compatibility):
460 attributes_set.update({key: value for key, value in kwargs.items() if value is not _Unset})
462 # Private attributes:
463 self._qualifiers: set[Qualifier] = set() 1pdaghiqebjklsrfcmno
464 # Used to rebuild FieldInfo instances:
465 self._complete = True 1pdaghiqebjklsrfcmno
466 self._original_annotation: Any = PydanticUndefined 1pdaghiqebjklsrfcmno
467 self._original_assignment: Any = PydanticUndefined 1pdaghiqebjklsrfcmno
468 # Used to track whether the `FieldInfo` instance represents the data about a field (and is exposed in `model_fields`/`__pydantic_fields__`),
469 # or if it is the result of the `Field()` function being used as metadata in an `Annotated` type/as an assignment
470 # (not an ideal pattern, see https://github.com/pydantic/pydantic/issues/11122):
471 self._final = False 1pdaghiqebjklsrfcmno
473 @staticmethod 1pdaghiqebjklsrfcmno
474 def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo: 1pdaghiqebjklsrfcmno
475 """Create a new `FieldInfo` object with the `Field` function.
477 Args:
478 default: The default value for the field. Defaults to Undefined.
479 **kwargs: Additional arguments dictionary.
481 Raises:
482 TypeError: If 'annotation' is passed as a keyword argument.
484 Returns:
485 A new FieldInfo object with the given parameters.
487 Example:
488 This is how you can create a field with default value like this:
490 ```python
491 import pydantic
493 class MyModel(pydantic.BaseModel):
494 foo: int = pydantic.Field(4)
495 ```
496 """
497 if 'annotation' in kwargs: 1pdaghiqebjklsrfcmno
498 raise TypeError('"annotation" is not permitted as a Field keyword argument') 1pdaghiqebjklrfcmno
499 return FieldInfo(default=default, **kwargs) 1pdaghiqebjklsrfcmno
501 @staticmethod 1pdaghiqebjklsrfcmno
502 def from_annotation(annotation: type[Any], *, _source: AnnotationSource = AnnotationSource.ANY) -> FieldInfo: 1pdaghiqebjklsrfcmno
503 """Creates a `FieldInfo` instance from a bare annotation.
505 This function is used internally to create a `FieldInfo` from a bare annotation like this:
507 ```python
508 import pydantic
510 class MyModel(pydantic.BaseModel):
511 foo: int # <-- like this
512 ```
514 We also account for the case where the annotation can be an instance of `Annotated` and where
515 one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
517 ```python
518 from typing import Annotated
520 import annotated_types
522 import pydantic
524 class MyModel(pydantic.BaseModel):
525 foo: Annotated[int, annotated_types.Gt(42)]
526 bar: Annotated[int, pydantic.Field(gt=42)]
527 ```
529 Args:
530 annotation: An annotation object.
532 Returns:
533 An instance of the field metadata.
534 """
535 try: 1pdaghiqebjklsrfcmno
536 inspected_ann = inspect_annotation( 1pdaghiqebjklsrfcmno
537 annotation,
538 annotation_source=_source,
539 unpack_type_aliases='skip',
540 )
541 except ForbiddenQualifier as e: 1pdaghiqebjklrfcmno
542 raise PydanticForbiddenQualifier(e.qualifier, annotation) 1pdaghiqebjklrfcmno
544 # TODO check for classvar and error?
546 # No assigned value, this happens when using a bare `Final` qualifier (also for other
547 # qualifiers, but they shouldn't appear here). In this case we infer the type as `Any`
548 # because we don't have any assigned value.
549 type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type 1pdaghiqebjklsrfcmno
550 final = 'final' in inspected_ann.qualifiers 1pdaghiqebjklsrfcmno
551 metadata = inspected_ann.metadata 1pdaghiqebjklsrfcmno
553 attr_overrides = {'annotation': type_expr} 1pdaghiqebjklsrfcmno
554 if final: 1pdaghiqebjklsrfcmno
555 attr_overrides['frozen'] = True 1pdaghiqebjklrfcmno
556 field_info = FieldInfo._construct(metadata, **attr_overrides) 1pdaghiqebjklsrfcmno
557 field_info._qualifiers = inspected_ann.qualifiers 1pdaghiqebjklsrfcmno
558 field_info._final = True 1pdaghiqebjklsrfcmno
559 return field_info 1pdaghiqebjklsrfcmno
561 @staticmethod 1pdaghiqebjklsrfcmno
562 def from_annotated_attribute( 1pdaghiqebjklsrfcmno
563 annotation: type[Any], default: Any, *, _source: AnnotationSource = AnnotationSource.ANY
564 ) -> FieldInfo:
565 """Create `FieldInfo` from an annotation with a default value.
567 This is used in cases like the following:
569 ```python
570 from typing import Annotated
572 import annotated_types
574 import pydantic
576 class MyModel(pydantic.BaseModel):
577 foo: int = 4 # <-- like this
578 bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
579 spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
580 ```
582 Args:
583 annotation: The type annotation of the field.
584 default: The default value of the field.
586 Returns:
587 A field object with the passed values.
588 """
589 if annotation is not MISSING and annotation is default: 1pdaghiqebjklsrfcmno
590 raise PydanticUserError( 1pdaghiqebjklrfcmno
591 'Error when building FieldInfo from annotated attribute. '
592 "Make sure you don't have any field name clashing with a type annotation.",
593 code='unevaluable-type-annotation',
594 )
596 try: 1pdaghiqebjklsrfcmno
597 inspected_ann = inspect_annotation( 1pdaghiqebjklsrfcmno
598 annotation,
599 annotation_source=_source,
600 unpack_type_aliases='skip',
601 )
602 except ForbiddenQualifier as e: 1pdaghiqebjklrfcmno
603 raise PydanticForbiddenQualifier(e.qualifier, annotation) 1pdaghiqebjklrfcmno
605 # TODO check for classvar and error?
607 final = 'final' in inspected_ann.qualifiers 1pdaghiqebjklsrfcmno
608 if inspected_ann.type is not UNKNOWN: 1pdaghiqebjklsrfcmno
609 type_expr: Any = inspected_ann.type 1pdaghiqebjklsrfcmno
610 elif final: 1pdaghiqebjklrfcmno
611 # Bare `Final` qualifier (e.g. `x: Final = 1`), infer the type from the default as type checkers do:
612 type_expr = _infer_type_from_default(default) 1pdaghiqebjklrfcmno
613 else:
614 type_expr = Any 1pdaghiqebjklrfcmno
615 metadata = inspected_ann.metadata 1pdaghiqebjklsrfcmno
617 # HACK 1: the order in which the metadata is merged is inconsistent; we need to prepend
618 # metadata from the assignment at the beginning of the metadata. Changing this is only
619 # possible in v3 (at least). See https://github.com/pydantic/pydantic/issues/10507
620 prepend_metadata: list[Any] | None = None 1pdaghiqebjklsrfcmno
621 attr_overrides = {'annotation': type_expr} 1pdaghiqebjklsrfcmno
622 if final: 1pdaghiqebjklsrfcmno
623 attr_overrides['frozen'] = True 1pdaghiqebjklrfcmno
625 # HACK 2: FastAPI is subclassing `FieldInfo` and historically expected the actual
626 # instance's type to be preserved when constructing new models with its subclasses as assignments.
627 # This code is never reached by Pydantic itself, and in an ideal world this shouldn't be necessary.
628 if not metadata and isinstance(default, FieldInfo) and type(default) is not FieldInfo: 1pdaghiqebjklsrfcmno
629 field_info = default._copy() 1pdaghiqebjklrfcmno
630 field_info._attributes_set.update(attr_overrides) 1pdaghiqebjklrfcmno
631 for k, v in attr_overrides.items(): 1pdaghiqebjklrfcmno
632 setattr(field_info, k, v) 1pdaghiqebjklrfcmno
633 return field_info 1pdaghiqebjklrfcmno
635 if isinstance(default, FieldInfo): 1pdaghiqebjklsrfcmno
636 default_copy = default._copy() # Copy unnecessary when we remove HACK 1. 1pdaghiqebjklsrfcmno
637 prepend_metadata = default_copy.metadata 1pdaghiqebjklsrfcmno
638 default_copy.metadata = [] 1pdaghiqebjklsrfcmno
639 metadata = metadata + [default_copy] 1pdaghiqebjklsrfcmno
640 if 'init_var' in inspected_ann.qualifiers: 1pdaghiqebjklsrfcmno
641 # Only relevant for dataclasses, when `f: InitVar[<type>] = Field(...)`
642 # is used:
643 attr_overrides['init_var'] = True 1pdaghiqebjklrfcmno
644 elif isinstance(default, dataclasses.Field): 1pdaghiqebjklsrfcmno
645 from_field = FieldInfo._from_dataclass_field(default) 1pdaghiqebjklsrfcmno
646 prepend_metadata = from_field.metadata # Unnecessary when we remove HACK 1. 1pdaghiqebjklsrfcmno
647 from_field.metadata = [] 1pdaghiqebjklsrfcmno
648 metadata = metadata + [from_field] 1pdaghiqebjklsrfcmno
649 if 'init_var' in inspected_ann.qualifiers: 1pdaghiqebjklsrfcmno
650 attr_overrides['init_var'] = True 1pdaghiqebjklsrfcmno
651 if (init := getattr(default, 'init', None)) is not None: 651 ↛ 653line 651 didn't jump to line 653 because the condition on line 651 was always true1pdaghiqebjklsrfcmno
652 attr_overrides['init'] = init 1pdaghiqebjklsrfcmno
653 if (kw_only := getattr(default, 'kw_only', None)) is not None: 653 ↛ 659line 653 didn't jump to line 659 because the condition on line 653 was always true1pdaghiqebjklsrfcmno
654 attr_overrides['kw_only'] = kw_only 1pdaghiqebjklsrfcmno
655 else:
656 # `default` is the actual default value
657 attr_overrides['default'] = default 1pdaghiqebjklsrfcmno
659 field_info = FieldInfo._construct( 1pdaghiqebjklsrfcmno
660 prepend_metadata + metadata if prepend_metadata is not None else metadata, **attr_overrides
661 )
662 field_info._qualifiers = inspected_ann.qualifiers 1pdaghiqebjklsrfcmno
663 field_info._final = True 1pdaghiqebjklsrfcmno
664 return field_info 1pdaghiqebjklsrfcmno
666 @classmethod 1pdaghiqebjklsrfcmno
667 def _construct(cls, metadata: list[Any], **attr_overrides: Any) -> Self: 1pdaghiqebjklsrfcmno
668 """Construct the final `FieldInfo` instance, by merging the possibly existing `FieldInfo` instances from the metadata.
670 With the following example:
672 ```python {test="skip" lint="skip"}
673 class Model(BaseModel):
674 f: Annotated[int, Gt(1), Field(description='desc', lt=2)]
675 ```
677 `metadata` refers to the metadata elements of the `Annotated` form. This metadata is iterated over from left to right:
679 - If the element is a `Field()` function (which is itself a `FieldInfo` instance), the field attributes (such as
680 `description`) are saved to be set on the final `FieldInfo` instance.
681 On the other hand, some kwargs (such as `lt`) are stored as `metadata` (see `FieldInfo.__init__()`, calling
682 `FieldInfo._collect_metadata()`). In this case, the final metadata list is extended with the one from this instance.
683 - Else, the element is considered as a single metadata object, and is appended to the final metadata list.
685 Args:
686 metadata: The list of metadata elements to merge together. If the `FieldInfo` instance to be constructed is for
687 a field with an assigned `Field()`, this `Field()` assignment should be added as the last element of the
688 provided metadata.
689 **attr_overrides: Extra attributes that should be set on the final merged `FieldInfo` instance.
691 Returns:
692 The final merged `FieldInfo` instance.
693 """
694 merged_metadata: list[Any] = [] 1pdaghiqebjklsrfcmno
695 merged_kwargs: dict[str, Any] = {} 1pdaghiqebjklsrfcmno
697 for meta in metadata: 1pdaghiqebjklsrfcmno
698 if isinstance(meta, FieldInfo): 1pdaghiqebjklsrfcmno
699 merged_metadata.extend(meta.metadata) 1pdaghiqebjklsrfcmno
701 new_js_extra: JsonDict | None = None 1pdaghiqebjklsrfcmno
702 current_js_extra = meta.json_schema_extra 1pdaghiqebjklsrfcmno
703 if current_js_extra is not None and 'json_schema_extra' in merged_kwargs: 1pdaghiqebjklsrfcmno
704 # We need to merge `json_schema_extra`'s:
705 existing_js_extra = merged_kwargs['json_schema_extra'] 1pdaghiqebjklrfcmno
706 if isinstance(existing_js_extra, dict): 1pdaghiqebjklrfcmno
707 if isinstance(current_js_extra, dict): 1pdaghiqebjklrfcmno
708 new_js_extra = { 1pdaghiqebjklrfcmno
709 **existing_js_extra,
710 **current_js_extra,
711 }
712 elif callable(current_js_extra): 712 ↛ 745line 712 didn't jump to line 745 because the condition on line 712 was always true1pdaghiqebjklrfcmno
713 # The `callable` is ignored, so we keep the existing `dict`. This needs to be set
714 # explicitly as `merged_kwargs` is otherwise overridden with `meta._attributes_set`
715 # (which contains the `callable`) below.
716 new_js_extra = existing_js_extra 1pdaghiqebjklrfcmno
717 warn( 1pdaghiqebjklrfcmno
718 'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
719 'The `callable` type is being ignored. '
720 "If you'd like support for this behavior, please open an issue on pydantic.",
721 UserWarning,
722 )
723 elif callable(existing_js_extra) and isinstance(current_js_extra, dict): 723 ↛ 745line 723 didn't jump to line 745 because the condition on line 723 was always true1pdaghiqebjklrfcmno
724 warn( 1pdaghiqebjklrfcmno
725 'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
726 'The `callable` type is being ignored. '
727 "If you'd like support for this behavior, please open an issue on pydantic.",
728 UserWarning,
729 )
731 # HACK: It is common for users to define "make model partial" (or similar) utilities, that
732 # convert all model fields to be optional (i.e. have a default value). To do so, they mutate
733 # each `FieldInfo` instance from `model_fields` to set a `default`, and use `create_model()`
734 # with `Annotated[<orig_type> | None, mutated_field_info]`` as an annotation. However, such
735 # mutations (by doing simple assignments) are only accidentally working, because we also
736 # need to track attributes explicitly set in `_attributes_set` (relying on default values for
737 # each attribute is *not* enough, for instance with `Annotated[int, Field(alias='a'), Field(alias=None)]`
738 # the resulting `FieldInfo` should have `alias=None`).
739 # To mitigate this, we add a special case when a "final" `FieldInfo` instance (that is an instance coming
740 # from `model_fields`) is used in annotated metadata (or assignment). In this case, we assume *all* attributes
741 # were explicitly set, and as such we use all of them (and this will correctly pick up the mutations).
742 # In theory, this shouldn't really be supported, you are only supposed to use the `Field()` function, not
743 # a `FieldInfo` instance directly (granted, `Field()` returns a `FieldInfo`, see
744 # https://github.com/pydantic/pydantic/issues/11122):
745 if meta._final: 1pdaghiqebjklsrfcmno
746 merged_kwargs.update({attr: getattr(meta, attr) for attr in _Attrs}) 1pdaghiqebjklrfcmno
747 else:
748 merged_kwargs.update(meta._attributes_set) 1pdaghiqebjklsrfcmno
750 if new_js_extra is not None: 1pdaghiqebjklsrfcmno
751 merged_kwargs['json_schema_extra'] = new_js_extra 1pdaghiqebjklrfcmno
752 elif typing_objects.is_deprecated(meta): 1pdaghiqebjklrfcmno
753 merged_kwargs['deprecated'] = meta 1pdaghiqebjklrfcmno
754 else:
755 merged_metadata.append(meta) 1pdaghiqebjklrfcmno
757 merged_kwargs.update(attr_overrides) 1pdaghiqebjklsrfcmno
758 merged_field_info = cls(**merged_kwargs) 1pdaghiqebjklsrfcmno
759 merged_field_info.metadata = merged_metadata 1pdaghiqebjklsrfcmno
760 return merged_field_info 1pdaghiqebjklsrfcmno
762 @staticmethod 1pdaghiqebjklsrfcmno
763 def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo: 1pdaghiqebjklsrfcmno
764 """Return a new `FieldInfo` instance from a `dataclasses.Field` instance.
766 Args:
767 dc_field: The `dataclasses.Field` instance to convert.
769 Returns:
770 The corresponding `FieldInfo` instance.
772 Raises:
773 TypeError: If any of the `FieldInfo` kwargs does not match the `dataclass.Field` kwargs.
774 """
775 default = dc_field.default 1pdaghiqebjklsrfcmno
776 if default is dataclasses.MISSING: 1pdaghiqebjklsrfcmno
777 default = _Unset 1pdaghiqebjklsrfcmno
779 if dc_field.default_factory is dataclasses.MISSING: 1pdaghiqebjklsrfcmno
780 default_factory = _Unset 1pdaghiqebjklsrfcmno
781 else:
782 default_factory = dc_field.default_factory 1pdaghiqebjklrfcmno
784 # use the `Field` function so in correct kwargs raise the correct `TypeError`
785 dc_field_metadata = {k: v for k, v in dc_field.metadata.items() if k in _FIELD_ARG_NAMES} 1pdaghiqebjklsrfcmno
786 if sys.version_info >= (3, 14) and dc_field.doc is not None: 1pdaghiqebjklsrfcmno
787 dc_field_metadata['description'] = dc_field.doc 1ghijklmno
788 return Field(default=default, default_factory=default_factory, repr=dc_field.repr, **dc_field_metadata) # pyright: ignore[reportCallIssue] 1pdaghiqebjklsrfcmno
790 @staticmethod 1pdaghiqebjklsrfcmno
791 def _collect_metadata(kwargs: dict[str, Any]) -> list[Any]: 1pdaghiqebjklsrfcmno
792 """Collect annotations from kwargs.
794 Args:
795 kwargs: Keyword arguments passed to the function.
797 Returns:
798 A list of metadata objects - a combination of `annotated_types.BaseMetadata` and
799 `PydanticMetadata`.
800 """
801 metadata: list[Any] = [] 1pdaghiqebjklrfcmno
802 general_metadata = {} 1pdaghiqebjklrfcmno
803 for key, value in list(kwargs.items()): 1pdaghiqebjklrfcmno
804 try: 1pdaghiqebjklrfcmno
805 marker = FieldInfo.metadata_lookup[key] 1pdaghiqebjklrfcmno
806 except KeyError:
807 continue
809 del kwargs[key] 1pdaghiqebjklrfcmno
810 if value is not None: 1pdaghiqebjklrfcmno
811 if marker is None: 1pdaghiqebjklrfcmno
812 general_metadata[key] = value 1pdaghiqebjklrfcmno
813 else:
814 metadata.append(marker(value)) 1pdaghiqebjklrfcmno
815 if general_metadata: 1pdaghiqebjklrfcmno
816 metadata.append(_fields.pydantic_general_metadata(**general_metadata)) 1pdaghiqebjklrfcmno
817 return metadata 1pdaghiqebjklrfcmno
819 @property 1pdaghiqebjklsrfcmno
820 def deprecation_message(self) -> str | None: 1pdaghiqebjklsrfcmno
821 """The deprecation message to be emitted, or `None` if not set."""
822 if self.deprecated is None: 1pdaghiqebjklsrfcmno
823 return None 1pdaghiqebjklsrfcmno
824 if isinstance(self.deprecated, bool): 1pdaghiqebjklrfcmno
825 return 'deprecated' if self.deprecated else None 1pdaghiqebjklrfcmno
826 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1pdaghiqebjklrfcmno
828 @property 1pdaghiqebjklsrfcmno
829 def default_factory_takes_validated_data(self) -> bool | None: 1pdaghiqebjklsrfcmno
830 """Whether the provided default factory callable has a validated data parameter.
832 Returns `None` if no default factory is set.
833 """
834 if self.default_factory is not None: 1pdaghiqebjklrfcmno
835 return _fields.takes_validated_data_argument(self.default_factory) 1pdaghiqebjklrfcmno
837 @overload 1pdaghiqebjklsrfcmno
838 def get_default( 1pdaghiqebjklsrfcmno
839 self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None 1pdaghiqebjklsrfcmno
840 ) -> Any: ... 1daebsfc
842 @overload 1pdaghiqebjklsrfcmno
843 def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ... 1pdaghiqebjklsrfcmno
845 def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any: 1pdaghiqebjklsrfcmno
846 """Get the default value.
848 We expose an option for whether to call the default_factory (if present), as calling it may
849 result in side effects that we want to avoid. However, there are times when it really should
850 be called (namely, when instantiating a model via `model_construct`).
852 Args:
853 call_default_factory: Whether to call the default factory or not.
854 validated_data: The already validated data to be passed to the default factory.
856 Returns:
857 The default value, calling the default factory if requested or `PydanticUndefined` if not set.
858 """
859 return _fields.resolve_default_value( 1pdaghiqebjklrfcmno
860 default=self.default,
861 default_factory=self.default_factory,
862 default_factory_takes_validated_data_argument=self.default_factory_takes_validated_data,
863 validated_data=validated_data,
864 call_default_factory=call_default_factory,
865 )
867 def is_required(self) -> bool: 1pdaghiqebjklsrfcmno
868 """Check if the field is required (i.e., does not have a default value or factory).
870 Returns:
871 `True` if the field is required, `False` otherwise.
872 """
873 return self.default is PydanticUndefined and self.default_factory is None 1pdaghiqebjklsrfcmno
875 def rebuild_annotation(self) -> Any: 1pdaghiqebjklsrfcmno
876 """Attempts to rebuild the original annotation for use in function signatures.
878 If metadata is present, it adds it to the original annotation using
879 `Annotated`. Otherwise, it returns the original annotation as-is.
881 Note that because the metadata has been flattened, the original annotation
882 may not be reconstructed exactly as originally provided, e.g. if the original
883 type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
885 Returns:
886 The rebuilt annotation.
887 """
888 if not self.metadata: 1pdaghiqebjklrfcmno
889 return self.annotation 1pdaghiqebjklrfcmno
890 else:
891 # Annotated arguments must be a tuple
892 return Annotated[(self.annotation, *self.metadata)] # type: ignore 1pdaghiqebjklrfcmno
894 def apply_typevars_map( 1pdaghiqebjklsrfcmno
895 self,
896 typevars_map: Mapping[TypeVar, Any] | None,
897 globalns: GlobalsNamespace | None = None,
898 localns: MappingNamespace | None = None,
899 ) -> None:
900 """Apply a `typevars_map` to the annotation.
902 This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
904 This method applies the `typevars_map` to the annotation in place.
906 Args:
907 typevars_map: A dictionary mapping type variables to their concrete types.
908 globalns: The globals namespace to use during type annotation evaluation.
909 localns: The locals namespace to use during type annotation evaluation.
911 See Also:
912 pydantic._internal._generics.replace_types is used for replacing the typevars with
913 their concrete types.
914 """
915 annotation = _generics.replace_types(self.annotation, typevars_map) 1pdaghiqebjklrfcmno
916 annotation, evaluated = _typing_extra.try_eval_type(annotation, globalns, localns) 1pdaghiqebjklrfcmno
917 self.annotation = annotation 1pdaghiqebjklrfcmno
918 if not evaluated: 918 ↛ 919line 918 didn't jump to line 919 because the condition on line 918 was never true1pdaghiqebjklrfcmno
919 self._complete = False
920 self._original_annotation = self.annotation
922 def asdict(self) -> _FieldInfoAsDict: 1pdaghiqebjklsrfcmno
923 """Return a dictionary representation of the `FieldInfo` instance.
925 The returned value is a dictionary with three items:
927 * `annotation`: The type annotation of the field.
928 * `metadata`: The metadata list.
929 * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
930 """
931 return { 1pdaghiqebjklrfcmno
932 'annotation': self.annotation,
933 'metadata': self.metadata,
934 'attributes': {attr: getattr(self, attr) for attr in _Attrs},
935 }
937 def _copy(self) -> Self: 1pdaghiqebjklsrfcmno
938 """Return a copy of the `FieldInfo` instance."""
939 # Note: we can't define a custom `__copy__()`, as `FieldInfo` is being subclassed
940 # by some third-party libraries with extra attributes defined (and as `FieldInfo`
941 # is slotted, we can't make a copy of the `__dict__`).
942 if type(self) is FieldInfo: 1pdaghiqebjklsrfcmno
943 # Fast-path if the instance isn't a subclass (`copy.copy()` relies on pickling which is slower):
944 copied = FieldInfo.__new__(FieldInfo) 1pdaghiqebjklsrfcmno
945 for attr_name in FieldInfo.__slots__: 1pdaghiqebjklsrfcmno
946 setattr(copied, attr_name, getattr(self, attr_name)) 1pdaghiqebjklsrfcmno
947 else:
948 copied = copy(self) 1pdaghiqebjklrfcmno
950 for attr_name in ('metadata', '_attributes_set', '_qualifiers'): 1pdaghiqebjklsrfcmno
951 # Apply "deep-copy" behavior on collections attributes:
952 setattr(copied, attr_name, getattr(copied, attr_name).copy()) 1pdaghiqebjklsrfcmno
954 return copied # pyright: ignore[reportReturnType] 1pdaghiqebjklsrfcmno
956 def __repr_args__(self) -> ReprArgs: 1pdaghiqebjklsrfcmno
957 yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation)) 1pdaghiqebjklrfcmno
958 yield 'required', self.is_required() 1pdaghiqebjklrfcmno
960 for s in self.__slots__: 1pdaghiqebjklrfcmno
961 # TODO: properly make use of the protocol (https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol)
962 # By yielding a three-tuple:
963 if s in ( 1pdaghiqebjklrfcmno
964 'annotation',
965 '_attributes_set',
966 '_qualifiers',
967 '_complete',
968 '_original_assignment',
969 '_original_annotation',
970 '_final',
971 ):
972 continue 1pdaghiqebjklrfcmno
973 elif s == 'metadata' and not self.metadata: 1pdaghiqebjklrfcmno
974 continue 1pdaghiqebjklrfcmno
975 elif s == 'repr' and self.repr is True: 1pdaghiqebjklrfcmno
976 continue 1pdaghiqebjklrfcmno
977 if s == 'frozen' and self.frozen is False: 1pdaghiqebjklrfcmno
978 continue 1pdaghiqebjklrfcmno
979 if s == 'validation_alias' and self.validation_alias == self.alias: 1pdaghiqebjklrfcmno
980 continue 1pdaghiqebjklrfcmno
981 if s == 'serialization_alias' and self.serialization_alias == self.alias: 1pdaghiqebjklrfcmno
982 continue 1pdaghiqebjklrfcmno
983 if s == 'default' and self.default is not PydanticUndefined: 1pdaghiqebjklrfcmno
984 yield 'default', self.default 1pdaghiqebjklrfcmno
985 elif s == 'default_factory' and self.default_factory is not None: 1pdaghiqebjklrfcmno
986 yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory)) 1pdaghiqebjklrfcmno
987 else:
988 value = getattr(self, s) 1pdaghiqebjklrfcmno
989 if value is not None and value is not PydanticUndefined: 1pdaghiqebjklrfcmno
990 yield s, value 1pdaghiqebjklrfcmno
993def _infer_type_from_default(default: Any) -> Any: 1pdaghiqebjklsrfcmno
994 if isinstance(default, FieldInfo): 1pdaghiqebjklrfcmno
995 default_value, default_factory = default.default, default.default_factory 1pdaghiqebjklrfcmno
996 elif isinstance(default, dataclasses.Field): 1pdaghiqebjklrfcmno
997 default_value = PydanticUndefined if default.default is dataclasses.MISSING else default.default 1pdaghiqebjklrfcmno
998 default_factory = None if default.default_factory is dataclasses.MISSING else default.default_factory 1pdaghiqebjklrfcmno
999 else:
1000 default_value, default_factory = default, None 1pdaghiqebjklrfcmno
1002 if default_value is not PydanticUndefined and default_value is not Ellipsis: 1pdaghiqebjklrfcmno
1003 return type(default_value) 1pdaghiqebjklrfcmno
1005 origin = get_origin(default_factory) 1pdaghiqebjklrfcmno
1006 if origin is not None and not ( 1pdaghiqebjklrfcmno
1007 typing_objects.is_annotated(origin) or typing_objects.is_literal(origin) or is_union_origin(origin)
1008 ):
1009 # e.g. `list[int]`:
1010 return default_factory 1pdaghiqebjklrfcmno
1011 if isinstance(default_factory, type): 1pdaghiqebjklrfcmno
1012 # e.g. `list` or `dict`, creating an empty instance of the type:
1013 return default_factory 1pdaghiqebjklrfcmno
1014 return Any 1pdaghiqebjklrfcmno
1017_Attrs = { 1pdaghiqebjklsrfcmno
1018 'default': ...,
1019 'default_factory': None,
1020 'alias': None,
1021 'alias_priority': None,
1022 'validation_alias': None,
1023 'serialization_alias': None,
1024 'title': None,
1025 'field_title_generator': None,
1026 'description': None,
1027 'examples': None,
1028 'exclude': None,
1029 'exclude_if': None,
1030 'discriminator': None,
1031 'deprecated': None,
1032 'json_schema_extra': None,
1033 'frozen': None,
1034 'validate_default': None,
1035 'repr': True,
1036 'init': None,
1037 'init_var': None,
1038 'kw_only': None,
1039}
1041_T = TypeVar('_T') 1pdaghiqebjklsrfcmno
1044# NOTE: Actual return type is 'FieldInfo', but we want to help type checkers
1045# to understand the magic that happens at runtime with the following overloads:
1046@overload # type hint the return value as `Any` to avoid type checking regressions when using `...`. 1pdaghiqebjklsrfcmno
1047def Field( 1pdaghiqebjklsrfcmno
1048 default: EllipsisType, 1daebsfc
1049 *,
1050 alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1051 alias_priority: int | None = _Unset, 1pdaghiqebjklsrfcmno
1052 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1pdaghiqebjklsrfcmno
1053 serialization_alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1054 title: str | None = _Unset, 1pdaghiqebjklsrfcmno
1055 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1pdaghiqebjklsrfcmno
1056 description: str | None = _Unset, 1pdaghiqebjklsrfcmno
1057 examples: list[Any] | None = _Unset, 1pdaghiqebjklsrfcmno
1058 exclude: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1059 exclude_if: Callable[[Any], bool] | None = _Unset, 1pdaghiqebjklsrfcmno
1060 discriminator: str | types.Discriminator | None = _Unset, 1pdaghiqebjklsrfcmno
1061 deprecated: Deprecated | str | bool | None = _Unset, 1pdaghiqebjklsrfcmno
1062 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1pdaghiqebjklsrfcmno
1063 frozen: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1064 validate_default: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1065 repr: bool = _Unset, 1pdaghiqebjklsrfcmno
1066 init: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1067 init_var: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1068 kw_only: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1069 pattern: str | re.Pattern[str] | None = _Unset, 1pdaghiqebjklsrfcmno
1070 strict: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1071 coerce_numbers_to_str: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1072 gt: annotated_types.SupportsGt | None = _Unset, 1pdaghiqebjklsrfcmno
1073 ge: annotated_types.SupportsGe | None = _Unset, 1pdaghiqebjklsrfcmno
1074 lt: annotated_types.SupportsLt | None = _Unset, 1pdaghiqebjklsrfcmno
1075 le: annotated_types.SupportsLe | None = _Unset, 1pdaghiqebjklsrfcmno
1076 multiple_of: float | None = _Unset, 1pdaghiqebjklsrfcmno
1077 allow_inf_nan: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1078 max_digits: int | None = _Unset, 1pdaghiqebjklsrfcmno
1079 decimal_places: int | None = _Unset, 1pdaghiqebjklsrfcmno
1080 min_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1081 max_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1082 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1pdaghiqebjklsrfcmno
1083 fail_fast: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1084) -> Any: ... 1daebsfc
1085@overload # `default` argument set, validate_default=True (no type checking on the default value) 1pdaghiqebjklsrfcmno
1086def Field( 1pdaghiqebjklsrfcmno
1087 default: Any, 1daebsfc
1088 *,
1089 alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1090 alias_priority: int | None = _Unset, 1pdaghiqebjklsrfcmno
1091 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1pdaghiqebjklsrfcmno
1092 serialization_alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1093 title: str | None = _Unset, 1pdaghiqebjklsrfcmno
1094 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1pdaghiqebjklsrfcmno
1095 description: str | None = _Unset, 1pdaghiqebjklsrfcmno
1096 examples: list[Any] | None = _Unset, 1pdaghiqebjklsrfcmno
1097 exclude: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1098 exclude_if: Callable[[Any], bool] | None = _Unset, 1pdaghiqebjklsrfcmno
1099 discriminator: str | types.Discriminator | None = _Unset, 1pdaghiqebjklsrfcmno
1100 deprecated: Deprecated | str | bool | None = _Unset, 1pdaghiqebjklsrfcmno
1101 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1pdaghiqebjklsrfcmno
1102 frozen: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1103 validate_default: Literal[True], 1daebsfc
1104 repr: bool = _Unset, 1pdaghiqebjklsrfcmno
1105 init: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1106 init_var: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1107 kw_only: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1108 pattern: str | re.Pattern[str] | None = _Unset, 1pdaghiqebjklsrfcmno
1109 strict: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1110 coerce_numbers_to_str: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1111 gt: annotated_types.SupportsGt | None = _Unset, 1pdaghiqebjklsrfcmno
1112 ge: annotated_types.SupportsGe | None = _Unset, 1pdaghiqebjklsrfcmno
1113 lt: annotated_types.SupportsLt | None = _Unset, 1pdaghiqebjklsrfcmno
1114 le: annotated_types.SupportsLe | None = _Unset, 1pdaghiqebjklsrfcmno
1115 multiple_of: float | None = _Unset, 1pdaghiqebjklsrfcmno
1116 allow_inf_nan: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1117 max_digits: int | None = _Unset, 1pdaghiqebjklsrfcmno
1118 decimal_places: int | None = _Unset, 1pdaghiqebjklsrfcmno
1119 min_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1120 max_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1121 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1pdaghiqebjklsrfcmno
1122 fail_fast: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1123) -> Any: ... 1daebsfc
1124@overload # `default` argument set, validate_default=False or unset 1pdaghiqebjklsrfcmno
1125def Field( 1pdaghiqebjklsrfcmno
1126 default: _T, 1daebsfc
1127 *,
1128 alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1129 alias_priority: int | None = _Unset, 1pdaghiqebjklsrfcmno
1130 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1pdaghiqebjklsrfcmno
1131 serialization_alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1132 title: str | None = _Unset, 1pdaghiqebjklsrfcmno
1133 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1pdaghiqebjklsrfcmno
1134 description: str | None = _Unset, 1pdaghiqebjklsrfcmno
1135 examples: list[Any] | None = _Unset, 1pdaghiqebjklsrfcmno
1136 exclude: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1137 # NOTE: to get proper type checking on `exclude_if`'s argument, we could use `_T` instead of `Any`. However,
1138 # this requires (at least for pyright) adding an additional overload where `exclude_if` is required (otherwise
1139 # `a: int = Field(default_factory=str)` results in a false negative).
1140 exclude_if: Callable[[Any], bool] | None = _Unset, 1pdaghiqebjklsrfcmno
1141 discriminator: str | types.Discriminator | None = _Unset, 1pdaghiqebjklsrfcmno
1142 deprecated: Deprecated | str | bool | None = _Unset, 1pdaghiqebjklsrfcmno
1143 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1pdaghiqebjklsrfcmno
1144 frozen: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1145 validate_default: Literal[False] = ..., 1pdaghiqebjklsrfcmno
1146 repr: bool = _Unset, 1pdaghiqebjklsrfcmno
1147 init: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1148 init_var: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1149 kw_only: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1150 pattern: str | re.Pattern[str] | None = _Unset, 1pdaghiqebjklsrfcmno
1151 strict: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1152 coerce_numbers_to_str: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1153 gt: annotated_types.SupportsGt | None = _Unset, 1pdaghiqebjklsrfcmno
1154 ge: annotated_types.SupportsGe | None = _Unset, 1pdaghiqebjklsrfcmno
1155 lt: annotated_types.SupportsLt | None = _Unset, 1pdaghiqebjklsrfcmno
1156 le: annotated_types.SupportsLe | None = _Unset, 1pdaghiqebjklsrfcmno
1157 multiple_of: float | None = _Unset, 1pdaghiqebjklsrfcmno
1158 allow_inf_nan: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1159 max_digits: int | None = _Unset, 1pdaghiqebjklsrfcmno
1160 decimal_places: int | None = _Unset, 1pdaghiqebjklsrfcmno
1161 min_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1162 max_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1163 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1pdaghiqebjklsrfcmno
1164 fail_fast: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1165) -> _T: ... 1daebsfc
1166@overload # `default_factory` argument set, validate_default=True (no type checking on the default value) 1pdaghiqebjklsrfcmno
1167def Field( # pyright: ignore[reportOverlappingOverload] 1pdaghiqebjklsrfcmno
1168 *,
1169 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any], 1daebsfc
1170 alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1171 alias_priority: int | None = _Unset, 1pdaghiqebjklsrfcmno
1172 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1pdaghiqebjklsrfcmno
1173 serialization_alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1174 title: str | None = _Unset, 1pdaghiqebjklsrfcmno
1175 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1pdaghiqebjklsrfcmno
1176 description: str | None = _Unset, 1pdaghiqebjklsrfcmno
1177 examples: list[Any] | None = _Unset, 1pdaghiqebjklsrfcmno
1178 exclude: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1179 exclude_if: Callable[[Any], bool] | None = _Unset, 1pdaghiqebjklsrfcmno
1180 discriminator: str | types.Discriminator | None = _Unset, 1pdaghiqebjklsrfcmno
1181 deprecated: Deprecated | str | bool | None = _Unset, 1pdaghiqebjklsrfcmno
1182 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1pdaghiqebjklsrfcmno
1183 frozen: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1184 validate_default: Literal[True], 1daebsfc
1185 repr: bool = _Unset, 1pdaghiqebjklsrfcmno
1186 init: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1187 init_var: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1188 kw_only: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1189 pattern: str | re.Pattern[str] | None = _Unset, 1pdaghiqebjklsrfcmno
1190 strict: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1191 coerce_numbers_to_str: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1192 gt: annotated_types.SupportsGt | None = _Unset, 1pdaghiqebjklsrfcmno
1193 ge: annotated_types.SupportsGe | None = _Unset, 1pdaghiqebjklsrfcmno
1194 lt: annotated_types.SupportsLt | None = _Unset, 1pdaghiqebjklsrfcmno
1195 le: annotated_types.SupportsLe | None = _Unset, 1pdaghiqebjklsrfcmno
1196 multiple_of: float | None = _Unset, 1pdaghiqebjklsrfcmno
1197 allow_inf_nan: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1198 max_digits: int | None = _Unset, 1pdaghiqebjklsrfcmno
1199 decimal_places: int | None = _Unset, 1pdaghiqebjklsrfcmno
1200 min_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1201 max_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1202 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1pdaghiqebjklsrfcmno
1203 fail_fast: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1204) -> Any: ... 1daebsfc
1205@overload # `default_factory` argument set, validate_default=False or unset 1pdaghiqebjklsrfcmno
1206def Field( 1pdaghiqebjklsrfcmno
1207 *,
1208 default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T], 1daebsfc
1209 alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1210 alias_priority: int | None = _Unset, 1pdaghiqebjklsrfcmno
1211 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1pdaghiqebjklsrfcmno
1212 serialization_alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1213 title: str | None = _Unset, 1pdaghiqebjklsrfcmno
1214 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1pdaghiqebjklsrfcmno
1215 description: str | None = _Unset, 1pdaghiqebjklsrfcmno
1216 examples: list[Any] | None = _Unset, 1pdaghiqebjklsrfcmno
1217 exclude: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1218 # NOTE: to get proper type checking on `exclude_if`'s argument, we could use `_T` instead of `Any`. However,
1219 # this requires (at least for pyright) adding an additional overload where `exclude_if` is required (otherwise
1220 # `a: int = Field(default_factory=str)` results in a false negative).
1221 exclude_if: Callable[[Any], bool] | None = _Unset, 1pdaghiqebjklsrfcmno
1222 discriminator: str | types.Discriminator | None = _Unset, 1pdaghiqebjklsrfcmno
1223 deprecated: Deprecated | str | bool | None = _Unset, 1pdaghiqebjklsrfcmno
1224 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1pdaghiqebjklsrfcmno
1225 frozen: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1226 validate_default: Literal[False] | None = _Unset, 1pdaghiqebjklsrfcmno
1227 repr: bool = _Unset, 1pdaghiqebjklsrfcmno
1228 init: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1229 init_var: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1230 kw_only: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1231 pattern: str | re.Pattern[str] | None = _Unset, 1pdaghiqebjklsrfcmno
1232 strict: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1233 coerce_numbers_to_str: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1234 gt: annotated_types.SupportsGt | None = _Unset, 1pdaghiqebjklsrfcmno
1235 ge: annotated_types.SupportsGe | None = _Unset, 1pdaghiqebjklsrfcmno
1236 lt: annotated_types.SupportsLt | None = _Unset, 1pdaghiqebjklsrfcmno
1237 le: annotated_types.SupportsLe | None = _Unset, 1pdaghiqebjklsrfcmno
1238 multiple_of: float | None = _Unset, 1pdaghiqebjklsrfcmno
1239 allow_inf_nan: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1240 max_digits: int | None = _Unset, 1pdaghiqebjklsrfcmno
1241 decimal_places: int | None = _Unset, 1pdaghiqebjklsrfcmno
1242 min_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1243 max_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1244 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1pdaghiqebjklsrfcmno
1245 fail_fast: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1246) -> _T: ... 1daebsfc
1247@overload 1pdaghiqebjklsrfcmno
1248def Field( # No default set 1pdaghiqebjklsrfcmno
1249 *,
1250 alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1251 alias_priority: int | None = _Unset, 1pdaghiqebjklsrfcmno
1252 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1pdaghiqebjklsrfcmno
1253 serialization_alias: str | None = _Unset, 1pdaghiqebjklsrfcmno
1254 title: str | None = _Unset, 1pdaghiqebjklsrfcmno
1255 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1pdaghiqebjklsrfcmno
1256 description: str | None = _Unset, 1pdaghiqebjklsrfcmno
1257 examples: list[Any] | None = _Unset, 1pdaghiqebjklsrfcmno
1258 exclude: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1259 exclude_if: Callable[[Any], bool] | None = _Unset, 1pdaghiqebjklsrfcmno
1260 discriminator: str | types.Discriminator | None = _Unset, 1pdaghiqebjklsrfcmno
1261 deprecated: Deprecated | str | bool | None = _Unset, 1pdaghiqebjklsrfcmno
1262 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1pdaghiqebjklsrfcmno
1263 frozen: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1264 validate_default: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1265 repr: bool = _Unset, 1pdaghiqebjklsrfcmno
1266 init: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1267 init_var: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1268 kw_only: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1269 pattern: str | re.Pattern[str] | None = _Unset, 1pdaghiqebjklsrfcmno
1270 strict: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1271 coerce_numbers_to_str: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1272 gt: annotated_types.SupportsGt | None = _Unset, 1pdaghiqebjklsrfcmno
1273 ge: annotated_types.SupportsGe | None = _Unset, 1pdaghiqebjklsrfcmno
1274 lt: annotated_types.SupportsLt | None = _Unset, 1pdaghiqebjklsrfcmno
1275 le: annotated_types.SupportsLe | None = _Unset, 1pdaghiqebjklsrfcmno
1276 multiple_of: float | None = _Unset, 1pdaghiqebjklsrfcmno
1277 allow_inf_nan: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1278 max_digits: int | None = _Unset, 1pdaghiqebjklsrfcmno
1279 decimal_places: int | None = _Unset, 1pdaghiqebjklsrfcmno
1280 min_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1281 max_length: int | None = _Unset, 1pdaghiqebjklsrfcmno
1282 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1pdaghiqebjklsrfcmno
1283 fail_fast: bool | None = _Unset, 1pdaghiqebjklsrfcmno
1284) -> Any: ... 1daebsfc
1285def Field( # noqa: C901 1pdaghiqebjklsrfcmno
1286 default: Any = PydanticUndefined,
1287 *,
1288 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = _Unset,
1289 alias: str | None = _Unset,
1290 alias_priority: int | None = _Unset,
1291 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
1292 serialization_alias: str | None = _Unset,
1293 title: str | None = _Unset,
1294 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
1295 description: str | None = _Unset,
1296 examples: list[Any] | None = _Unset,
1297 exclude: bool | None = _Unset,
1298 exclude_if: Callable[[Any], bool] | None = _Unset,
1299 discriminator: str | types.Discriminator | None = _Unset,
1300 deprecated: Deprecated | str | bool | None = _Unset,
1301 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
1302 frozen: bool | None = _Unset,
1303 validate_default: bool | None = _Unset,
1304 repr: bool = _Unset,
1305 init: bool | None = _Unset,
1306 init_var: bool | None = _Unset,
1307 kw_only: bool | None = _Unset,
1308 pattern: str | re.Pattern[str] | None = _Unset,
1309 strict: bool | None = _Unset,
1310 coerce_numbers_to_str: bool | None = _Unset,
1311 gt: annotated_types.SupportsGt | None = _Unset,
1312 ge: annotated_types.SupportsGe | None = _Unset,
1313 lt: annotated_types.SupportsLt | None = _Unset,
1314 le: annotated_types.SupportsLe | None = _Unset,
1315 multiple_of: float | None = _Unset,
1316 allow_inf_nan: bool | None = _Unset,
1317 max_digits: int | None = _Unset,
1318 decimal_places: int | None = _Unset,
1319 min_length: int | None = _Unset,
1320 max_length: int | None = _Unset,
1321 union_mode: Literal['smart', 'left_to_right'] = _Unset,
1322 fail_fast: bool | None = _Unset,
1323) -> Any:
1324 """!!! abstract "Usage Documentation"
1325 [Fields](../concepts/fields.md)
1327 Create a field for objects that can be configured.
1329 Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
1330 apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`.
1332 Note:
1333 - Any `_Unset` objects will be replaced by the corresponding default value of the `FieldInfo` constructor.
1335 Args:
1336 default: Default value if the field is not set.
1337 default_factory: A callable to generate the default value. The callable can either take 0 arguments
1338 (in which case it is called as is) or a single argument containing the already validated data.
1339 alias: The name to use for the attribute when validating or serializing by alias.
1340 This is often used for things like converting between snake and camel case.
1341 alias_priority: Priority of the alias. This affects whether an alias generator is used.
1342 validation_alias: Like `alias`, but only affects validation, not serialization.
1343 serialization_alias: Like `alias`, but only affects serialization, not validation.
1344 title: Human-readable title.
1345 field_title_generator: A callable that takes a field's name and info and returns title for it.
1346 description: Human-readable description.
1347 examples: Example values for this field.
1348 exclude: Whether to exclude the field from the model serialization.
1349 exclude_if: A callable that determines whether to exclude a field during serialization based on its value.
1350 discriminator: Field name or Discriminator for discriminating the type in a tagged union.
1351 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
1352 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
1353 json_schema_extra: A dict or callable to provide extra JSON schema properties.
1354 frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.
1355 validate_default: If `True`, apply validation to the default value every time you create an instance.
1356 Otherwise, for performance reasons, the default value of the field is trusted and not validated.
1357 repr: A boolean indicating whether to include the field in the `__repr__` output.
1358 init: Whether the field should be included in the constructor of the dataclass.
1359 (Only applies to dataclasses.)
1360 init_var: Whether the field should _only_ be included in the constructor of the dataclass.
1361 (Only applies to dataclasses.)
1362 kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
1363 (Only applies to dataclasses.)
1364 coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
1365 strict: If `True`, strict validation is applied to the field.
1366 See [Strict Mode](../concepts/strict_mode.md) for details.
1367 gt: Greater than. If set, value must be greater than this. Only applicable to numbers.
1368 ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.
1369 lt: Less than. If set, value must be less than this. Only applicable to numbers.
1370 le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.
1371 multiple_of: Value must be a multiple of this. Only applicable to numbers.
1372 min_length: Minimum length for iterables.
1373 max_length: Maximum length for iterables.
1374 pattern: Pattern for strings (a regular expression).
1375 allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to float and [`Decimal`][decimal.Decimal] numbers.
1376 max_digits: Maximum number of allowed digits for [`Decimal`][decimal.Decimal] numbers.
1377 decimal_places: Maximum number of decimal places allowed for numbers.
1378 union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`.
1379 See [Union Mode](../concepts/unions.md#union-modes) for details.
1380 fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected.
1381 This option can be applied only to iterable types (list, tuple, set, and frozenset).
1383 Returns:
1384 A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on
1385 type-annotated fields without causing a type error.
1386 """
1387 if ( 1pghiqjklrmno
1388 validation_alias
1389 and validation_alias is not _Unset
1390 and not isinstance(validation_alias, (str, AliasChoices, AliasPath))
1391 ):
1392 raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`') 1pdaghiqebjklrfcmno
1394 if serialization_alias in (_Unset, None) and isinstance(alias, str): 1pdaghiqebjklsrfcmno
1395 serialization_alias = alias 1pdaghiqebjklsrfcmno
1397 if validation_alias in (_Unset, None): 1pdaghiqebjklsrfcmno
1398 validation_alias = alias 1pdaghiqebjklsrfcmno
1400 return FieldInfo.from_field( 1pdaghiqebjklsrfcmno
1401 default,
1402 default_factory=default_factory,
1403 alias=alias,
1404 alias_priority=alias_priority,
1405 validation_alias=validation_alias,
1406 serialization_alias=serialization_alias,
1407 title=title,
1408 field_title_generator=field_title_generator,
1409 description=description,
1410 examples=examples,
1411 exclude=exclude,
1412 exclude_if=exclude_if,
1413 discriminator=discriminator,
1414 deprecated=deprecated,
1415 json_schema_extra=json_schema_extra,
1416 frozen=frozen,
1417 pattern=pattern,
1418 validate_default=validate_default,
1419 repr=repr,
1420 init=init,
1421 init_var=init_var,
1422 kw_only=kw_only,
1423 coerce_numbers_to_str=coerce_numbers_to_str,
1424 strict=strict,
1425 gt=gt,
1426 ge=ge,
1427 lt=lt,
1428 le=le,
1429 multiple_of=multiple_of,
1430 min_length=min_length,
1431 max_length=max_length,
1432 allow_inf_nan=allow_inf_nan,
1433 max_digits=max_digits,
1434 decimal_places=decimal_places,
1435 union_mode=union_mode,
1436 fail_fast=fail_fast,
1437 )
1440_FIELD_ARG_NAMES = set(inspect.signature(Field).parameters) 1pdaghiqebjklsrfcmno
1443class ModelPrivateAttr(_repr.Representation): 1pdaghiqebjklsrfcmno
1444 """A descriptor for private attributes in class models.
1446 !!! warning
1447 You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use
1448 the [`PrivateAttr()`][pydantic.fields.PrivateAttr] function.
1450 Attributes:
1451 default: The default value of the attribute if not provided.
1452 default_factory: A callable to generate the default value. The callable can either take 0 arguments
1453 (in which case it is called as is) or a single argument containing the validated data (the model's
1454 [`__dict__`][object.__dict__]) and the already initialized private attributes.
1455 """
1457 __slots__ = ('default', 'default_factory', '_default_factory_takes_validated_data') 1pdaghiqebjklsrfcmno
1459 def __init__( 1pdaghiqebjklsrfcmno
1460 self,
1461 default: Any = PydanticUndefined,
1462 *,
1463 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = None,
1464 ) -> None:
1465 if default is Ellipsis: 1pdaghiqebjklrfcmno
1466 self.default = PydanticUndefined 1pdaghiqebjklrfcmno
1467 else:
1468 self.default = default 1pdaghiqebjklrfcmno
1469 self.default_factory = default_factory 1pdaghiqebjklrfcmno
1470 self._default_factory_takes_validated_data: bool | None = _Unset 1pdaghiqebjklrfcmno
1472 if not TYPE_CHECKING: 1472 ↛ 1484line 1472 didn't jump to line 1484 because the condition on line 1472 was always true1pdaghiqebjklsrfcmno
1473 # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
1475 def __getattr__(self, item: str) -> Any: 1pdaghiqebjklsrfcmno
1476 """This function improves compatibility with custom descriptors by ensuring delegation happens
1477 as expected when the default value of a private attribute is a descriptor.
1478 """
1479 if item in {'__get__', '__set__', '__delete__'}: 1pdaghiqebjklrfcmno
1480 if hasattr(self.default, item): 1pdaghiqebjklrfcmno
1481 return getattr(self.default, item) 1pdaghiqebjklrfcmno
1482 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') 1pdaghiqebjklrfcmno
1484 def __set_name__(self, cls: type[Any], name: str) -> None: 1pdaghiqebjklsrfcmno
1485 """Preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487."""
1486 default = self.default 1pdaghiqebjklrfcmno
1487 if default is PydanticUndefined: 1pdaghiqebjklrfcmno
1488 return 1pdaghiqebjklrfcmno
1489 set_name = getattr(default, '__set_name__', None) 1pdaghiqebjklrfcmno
1490 if callable(set_name): 1pdaghiqebjklrfcmno
1491 set_name(cls, name) 1pdaghiqebjklrfcmno
1493 @property 1pdaghiqebjklsrfcmno
1494 def default_factory_takes_validated_data(self) -> bool | None: 1pdaghiqebjklsrfcmno
1495 """Whether the provided default factory callable has a validated data parameter.
1497 Returns `None` if no default factory is set.
1498 """
1499 if self._default_factory_takes_validated_data is not _Unset: 1pdaghiqebjklrfcmno
1500 return self._default_factory_takes_validated_data 1pdaghiqebjklrfcmno
1502 value: bool | None = None 1pdaghiqebjklrfcmno
1503 if self.default_factory is not None: 1pdaghiqebjklrfcmno
1504 value = _fields.takes_validated_data_argument(self.default_factory) 1pdaghiqebjklrfcmno
1506 self._default_factory_takes_validated_data = value 1pdaghiqebjklrfcmno
1507 return value 1pdaghiqebjklrfcmno
1509 @overload 1pdaghiqebjklsrfcmno
1510 def get_default( 1pdaghiqebjklsrfcmno
1511 self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None 1pdaghiqebjklsrfcmno
1512 ) -> Any: ... 1daebsfc
1514 @overload 1pdaghiqebjklsrfcmno
1515 def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ... 1pdaghiqebjklsrfcmno
1517 def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any: 1pdaghiqebjklsrfcmno
1518 """Get the default value.
1520 We expose an option for whether to call the default_factory (if present), as calling it may
1521 result in side effects that we want to avoid. However, there are times when it really should
1522 be called (namely, when instantiating a model via `model_construct`).
1524 Args:
1525 call_default_factory: Whether to call the default factory or not.
1526 validated_data: The already validated data to be passed to the default factory.
1528 Returns:
1529 The default value, calling the default factory if requested or `None` if not set.
1530 """
1531 return _fields.resolve_default_value( 1pdaghiqebjklrfcmno
1532 default=self.default,
1533 default_factory=self.default_factory,
1534 default_factory_takes_validated_data_argument=self.default_factory_takes_validated_data,
1535 validated_data=validated_data,
1536 call_default_factory=call_default_factory,
1537 )
1539 def __eq__(self, other: Any) -> bool: 1pdaghiqebjklsrfcmno
1540 return isinstance(other, self.__class__) and (self.default, self.default_factory) == ( 1pdaghiqebjklrfcmno
1541 other.default,
1542 other.default_factory,
1543 )
1545 def __repr_args__(self) -> ReprArgs: 1pdaghiqebjklsrfcmno
1546 if self.default is not PydanticUndefined: 1pdaghiqebjklrfcmno
1547 yield 'default', self.default 1pdaghiqebjklrfcmno
1548 if self.default_factory is not None: 1pdaghiqebjklrfcmno
1549 yield 'default_factory', self.default_factory 1pdaghiqebjklrfcmno
1552# NOTE: Actual return type is 'ModelPrivateAttr', but we want to help type checkers
1553# to understand the magic that happens at runtime.
1554@overload # `default` argument set 1pdaghiqebjklsrfcmno
1555def PrivateAttr( 1pdaghiqebjklsrfcmno
1556 default: _T, 1daebsfc
1557 *,
1558 init: Literal[False] = False, 1pdaghiqebjklsrfcmno
1559) -> _T: ... 1daebsfc
1560@overload # `default_factory` argument set 1pdaghiqebjklsrfcmno
1561def PrivateAttr( 1pdaghiqebjklsrfcmno
1562 *,
1563 default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T], 1daebsfc
1564 init: Literal[False] = False, 1pdaghiqebjklsrfcmno
1565) -> _T: ... 1daebsfc
1566@overload # No default set 1pdaghiqebjklsrfcmno
1567def PrivateAttr( 1pdaghiqebjklsrfcmno
1568 *,
1569 init: Literal[False] = False, 1pdaghiqebjklsrfcmno
1570) -> Any: ... 1daebsfc
1571def PrivateAttr( 1pdaghiqebjklsrfcmno
1572 default: Any = PydanticUndefined,
1573 *,
1574 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = None,
1575 init: Literal[False] = False,
1576) -> Any:
1577 """!!! abstract "Usage Documentation"
1578 [Private Model Attributes](../concepts/models.md#private-model-attributes)
1580 Indicates that an attribute is intended for private use and not handled during normal validation/serialization.
1582 Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner.
1584 Private attributes are stored in `__private_attributes__` on the model.
1586 Args:
1587 default: The attribute's default value. Defaults to Undefined.
1588 default_factory: A callable to generate the default value. The callable can either take 0 arguments
1589 (in which case it is called as is) or a single argument containing the validated data (the model's
1590 [`__dict__`][object.__dict__]) and the already initialized private attributes.
1591 If both `default` and `default_factory` are set, an error will be raised.
1592 init: Whether the attribute should be included in the constructor of the dataclass. Always `False`.
1594 Returns:
1595 An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class.
1597 Raises:
1598 TypeError: If both `default` and `default_factory` are set.
1599 """
1600 if default is not PydanticUndefined and default_factory is not None: 1pdaghiqebjklrfcmno
1601 raise TypeError('cannot specify both default and default_factory') 1pdaghiqebjklrfcmno
1603 return ModelPrivateAttr( 1pdaghiqebjklrfcmno
1604 default,
1605 default_factory=default_factory,
1606 )
1609@dataclasses.dataclass(slots=True) 1pdaghiqebjklsrfcmno
1610class ComputedFieldInfo: 1pdaghiqebjklsrfcmno
1611 """A container for data from `@computed_field` so that we can access it while building the pydantic-core schema.
1613 Attributes:
1614 decorator_repr: A class variable representing the decorator string, '@computed_field'.
1615 wrapped_property: The wrapped computed field property.
1616 return_type: The type of the computed field property's return value.
1617 alias: The alias of the property to be used during serialization.
1618 alias_priority: The priority of the alias. This affects whether an alias generator is used.
1619 title: Title of the computed field to include in the serialization JSON schema.
1620 field_title_generator: A callable that takes a field's name and info and returns title for it.
1621 description: Description of the computed field to include in the serialization JSON schema.
1622 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
1623 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
1624 examples: Example values of the computed field to include in the serialization JSON schema.
1625 json_schema_extra: A dict or callable to provide extra JSON schema properties.
1626 repr: A boolean indicating whether to include the field in the __repr__ output.
1627 """
1629 decorator_repr: ClassVar[str] = '@computed_field' 1pdaghiqebjklsrfcmno
1630 wrapped_property: property 1pdaghiqebjklsrfcmno
1631 return_type: Any 1pdaghiqebjklsrfcmno
1632 alias: str | None 1pdaghiqebjklsrfcmno
1633 alias_priority: int | None 1pdaghiqebjklsrfcmno
1634 exclude_if: Callable[[Any], bool] | None 1pdaghiqebjklsrfcmno
1635 title: str | None 1pdaghiqebjklsrfcmno
1636 field_title_generator: Callable[[str, ComputedFieldInfo], str] | None 1pdaghiqebjklsrfcmno
1637 description: str | None 1pdaghiqebjklsrfcmno
1638 deprecated: Deprecated | str | bool | None 1pdaghiqebjklsrfcmno
1639 examples: list[Any] | None 1pdaghiqebjklsrfcmno
1640 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1pdaghiqebjklsrfcmno
1641 repr: bool 1pdaghiqebjklsrfcmno
1642 # NOTE: if you add a new field, add it to the `__copy__()` implementation.
1644 def __copy__(self) -> Self: 1pdaghiqebjklsrfcmno
1645 return type(self)( 1pdaghiqebjklrfcmno
1646 wrapped_property=self.wrapped_property,
1647 return_type=self.return_type,
1648 alias=self.alias,
1649 alias_priority=self.alias_priority,
1650 exclude_if=self.exclude_if,
1651 title=self.title,
1652 field_title_generator=self.field_title_generator,
1653 description=self.description,
1654 deprecated=self.deprecated,
1655 examples=self.examples.copy() if isinstance(self.examples, list) else self.examples,
1656 json_schema_extra=self.json_schema_extra.copy()
1657 if isinstance(self.json_schema_extra, dict)
1658 else self.json_schema_extra,
1659 repr=self.repr,
1660 )
1662 @property 1pdaghiqebjklsrfcmno
1663 def deprecation_message(self) -> str | None: 1pdaghiqebjklsrfcmno
1664 """The deprecation message to be emitted, or `None` if not set."""
1665 if self.deprecated is None: 1pdaghiqebjklrfcmno
1666 return None 1pdaghiqebjklrfcmno
1667 if isinstance(self.deprecated, bool): 1pdaghiqebjklrfcmno
1668 return 'deprecated' if self.deprecated else None 1pdaghiqebjklrfcmno
1669 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1pdaghiqebjklrfcmno
1671 def _update_from_config(self, config_wrapper: ConfigWrapper, name: str) -> None: 1pdaghiqebjklsrfcmno
1672 """Update the instance from the configuration set on the class this computed field belongs to."""
1673 title_generator = self.field_title_generator or config_wrapper.field_title_generator 1pdaghiqebjklrfcmno
1674 if title_generator is not None and self.title is None: 1pdaghiqebjklrfcmno
1675 self.title = title_generator(name, self) 1pdaghiqebjklrfcmno
1676 if config_wrapper.alias_generator is not None: 1pdaghiqebjklrfcmno
1677 self._apply_alias_generator(config_wrapper.alias_generator, name) 1pdaghiqebjklrfcmno
1679 def _apply_alias_generator(self, alias_generator: Callable[[str], str] | AliasGenerator, name: str) -> None: 1pdaghiqebjklsrfcmno
1680 """Apply an alias generator to aliases if appropriate.
1682 Args:
1683 alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance.
1684 name: The name of the computed field from which to generate the alias.
1685 """
1686 # Apply an alias_generator if
1687 # 1. An alias is not specified
1688 # 2. An alias is specified, but the priority is <= 1
1690 if self.alias_priority is None or self.alias_priority <= 1 or self.alias is None: 1pdaghiqebjklrfcmno
1691 alias, _, serialization_alias = None, None, None 1pdaghiqebjklrfcmno
1693 if isinstance(alias_generator, AliasGenerator): 1pdaghiqebjklrfcmno
1694 alias, _, serialization_alias = alias_generator.generate_aliases(name) 1pdaghiqebjklrfcmno
1695 elif callable(alias_generator): 1695 ↛ 1701line 1695 didn't jump to line 1701 because the condition on line 1695 was always true1pdaghiqebjklrfcmno
1696 alias = alias_generator(name) 1pdaghiqebjklrfcmno
1698 # if priority is not set, we set to 1
1699 # which supports the case where the alias_generator from a child class is used
1700 # to generate an alias for a field in a parent class
1701 if self.alias_priority is None or self.alias_priority <= 1: 1701 ↛ 1707line 1701 didn't jump to line 1707 because the condition on line 1701 was always true1pdaghiqebjklrfcmno
1702 self.alias_priority = 1 1pdaghiqebjklrfcmno
1704 # if the priority is 1, then we set the aliases to the generated alias
1705 # note that we use the serialization_alias with priority over alias, as computed_field
1706 # aliases are used for serialization only (not validation)
1707 if self.alias_priority == 1: 1707 ↛ exitline 1707 didn't return from function '_apply_alias_generator' because the condition on line 1707 was always true1pdaghiqebjklrfcmno
1708 self.alias = _utils.get_first_not_none(serialization_alias, alias) 1pdaghiqebjklrfcmno
1711def _wrapped_property_is_private(property_: cached_property | property) -> bool: # type: ignore 1pdaghiqebjklsrfcmno
1712 """Returns true if provided property is private, False otherwise."""
1713 wrapped_name: str = '' 1pdaghiqebjklrfcmno
1715 if isinstance(property_, property): 1pdaghiqebjklrfcmno
1716 wrapped_name = getattr(property_.fget, '__name__', '') 1pdaghiqebjklrfcmno
1717 elif isinstance(property_, cached_property): # type: ignore 1pdaghiqebjklrfcmno
1718 wrapped_name = getattr(property_.func, '__name__', '') # type: ignore 1pdaghiqebjklrfcmno
1720 return wrapped_name.startswith('_') and not wrapped_name.startswith('__') 1pdaghiqebjklrfcmno
1723# this should really be `property[T], cached_property[T]` but property is not generic unlike cached_property
1724# See https://github.com/python/typing/issues/985 and linked issues
1725PropertyT = TypeVar('PropertyT') 1pdaghiqebjklsrfcmno
1728@overload 1pdaghiqebjklsrfcmno
1729def computed_field(func: PropertyT, /) -> PropertyT: ... 1pdaghiqebjklsrfcmno
1732@overload 1pdaghiqebjklsrfcmno
1733def computed_field( 1pdaghiqebjklsrfcmno
1734 *,
1735 alias: str | None = None, 1pdaghiqebjklsrfcmno
1736 alias_priority: int | None = None, 1pdaghiqebjklsrfcmno
1737 exclude_if: Callable[[Any], bool] | None = None, 1pdaghiqebjklsrfcmno
1738 title: str | None = None, 1pdaghiqebjklsrfcmno
1739 field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None, 1pdaghiqebjklsrfcmno
1740 description: str | None = None, 1pdaghiqebjklsrfcmno
1741 deprecated: Deprecated | str | bool | None = None, 1pdaghiqebjklsrfcmno
1742 examples: list[Any] | None = None, 1pdaghiqebjklsrfcmno
1743 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None, 1pdaghiqebjklsrfcmno
1744 repr: bool = True, 1pdaghiqebjklsrfcmno
1745 return_type: Any = PydanticUndefined, 1pdaghiqebjklsrfcmno
1746) -> Callable[[PropertyT], PropertyT]: ... 1daebsfc
1749def computed_field( 1pdaghiqebjklsrfcmno
1750 func: PropertyT | None = None,
1751 /,
1752 *,
1753 alias: str | None = None,
1754 alias_priority: int | None = None,
1755 exclude_if: Callable[[Any], bool] | None = None,
1756 title: str | None = None,
1757 field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None,
1758 description: str | None = None,
1759 deprecated: Deprecated | str | bool | None = None,
1760 examples: list[Any] | None = None,
1761 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
1762 repr: bool | None = None,
1763 return_type: Any = PydanticUndefined,
1764) -> PropertyT | Callable[[PropertyT], PropertyT]:
1765 """!!! abstract "Usage Documentation"
1766 [The `computed_field` decorator](../concepts/fields.md#the-computed_field-decorator)
1768 Decorator to include `property` and `cached_property` when serializing models or dataclasses.
1770 This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.
1772 ```python
1773 from pydantic import BaseModel, computed_field
1775 class Rectangle(BaseModel):
1776 width: int
1777 length: int
1779 @computed_field
1780 @property
1781 def area(self) -> int:
1782 return self.width * self.length
1784 print(Rectangle(width=3, length=2).model_dump())
1785 #> {'width': 3, 'length': 2, 'area': 6}
1786 ```
1788 If applied to functions not yet decorated with `@property` or `@cached_property`, the function is
1789 automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE,
1790 and confuse static type checkers, thus explicit use of `@property` is recommended.
1792 !!! warning "Mypy Warning"
1793 Even with the `@property` or `@cached_property` applied to your function before `@computed_field`,
1794 mypy may throw a `Decorated property not supported` error.
1795 See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information.
1796 To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line.
1798 [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error.
1800 ```python
1801 import random
1803 from pydantic import BaseModel, computed_field
1805 class Square(BaseModel):
1806 width: float
1808 @computed_field
1809 def area(self) -> float: # converted to a `property` by `computed_field`
1810 return round(self.width**2, 2)
1812 @area.setter
1813 def area(self, new_area: float) -> None:
1814 self.width = new_area**0.5
1816 @computed_field(alias='the magic number', repr=False)
1817 def random_number(self) -> int:
1818 return random.randint(0, 1_000)
1820 square = Square(width=1.3)
1822 # `random_number` does not appear in representation
1823 print(repr(square))
1824 #> Square(width=1.3, area=1.69)
1826 print(square.random_number)
1827 #> 3
1829 square.area = 4
1831 print(square.model_dump_json(by_alias=True))
1832 #> {"width":2.0,"area":4.0,"the magic number":3}
1833 ```
1835 !!! warning "Overriding with `computed_field`"
1836 You can't override a field from a parent class with a `computed_field` in the child class.
1837 `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either.
1838 See the example below:
1840 ```python
1841 from pydantic import BaseModel, computed_field
1843 class Parent(BaseModel):
1844 a: str
1846 try:
1848 class Child(Parent):
1849 @computed_field
1850 @property
1851 def a(self) -> str:
1852 return 'new a'
1854 except TypeError as e:
1855 print(e)
1856 '''
1857 Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
1858 '''
1859 ```
1861 Private properties decorated with `@computed_field` have `repr=False` by default.
1863 ```python
1864 from functools import cached_property
1866 from pydantic import BaseModel, computed_field
1868 class Model(BaseModel):
1869 foo: int
1871 @computed_field
1872 @cached_property
1873 def _private_cached_property(self) -> int:
1874 return -self.foo
1876 @computed_field
1877 @property
1878 def _private_property(self) -> int:
1879 return -self.foo
1881 m = Model(foo=1)
1882 print(repr(m))
1883 #> Model(foo=1)
1884 ```
1886 Args:
1887 func: the function to wrap.
1888 alias: alias to use when serializing this computed field, only used when `by_alias=True`
1889 alias_priority: priority of the alias. This affects whether an alias generator is used
1890 exclude_if: A callable that determines whether to exclude this computed field during serialization based on its value.
1891 title: Title to use when including this computed field in JSON Schema
1892 field_title_generator: A callable that takes a field's name and info and returns title for it.
1893 description: Description to use when including this computed field in JSON Schema, defaults to the function's
1894 docstring
1895 deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport).
1896 to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the
1897 `deprecated` decorator.
1898 examples: Example values to use when including this computed field in JSON Schema
1899 json_schema_extra: A dict or callable to provide extra JSON schema properties.
1900 repr: whether to include this computed field in model repr.
1901 Default is `False` for private properties and `True` for public properties.
1902 return_type: optional return for serialization logic to expect when serializing to JSON, if included
1903 this must be correct, otherwise a `TypeError` is raised.
1904 If you don't include a return type Any is used, which does runtime introspection to handle arbitrary
1905 objects.
1907 Returns:
1908 A proxy wrapper for the property.
1909 """
1911 def dec(f: Any) -> Any: 1pdaghiqebjklrfcmno
1912 nonlocal description, deprecated, return_type, alias_priority
1913 unwrapped = _decorators.unwrap_wrapped_function(f) 1pdaghiqebjklrfcmno
1915 if description is None and unwrapped.__doc__: 1pdaghiqebjklrfcmno
1916 description = inspect.cleandoc(unwrapped.__doc__) 1pdaghiqebjklrfcmno
1918 if deprecated is None and hasattr(unwrapped, '__deprecated__'): 1pdaghiqebjklrfcmno
1919 deprecated = unwrapped.__deprecated__ 1pdaghiqebjklrfcmno
1921 # if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now
1922 f = _decorators.ensure_property(f) 1pdaghiqebjklrfcmno
1923 alias_priority = (alias_priority or 2) if alias is not None else None 1pdaghiqebjklrfcmno
1925 if repr is None: 1pdaghiqebjklrfcmno
1926 repr_: bool = not _wrapped_property_is_private(property_=f) 1pdaghiqebjklrfcmno
1927 else:
1928 repr_ = repr 1pdaghiqebjklrfcmno
1930 dec_info = ComputedFieldInfo( 1pdaghiqebjklrfcmno
1931 f,
1932 return_type,
1933 alias,
1934 alias_priority,
1935 exclude_if,
1936 title,
1937 field_title_generator,
1938 description,
1939 deprecated,
1940 examples,
1941 json_schema_extra,
1942 repr_,
1943 )
1944 return _decorators.PydanticDescriptorProxy(f, dec_info) 1pdaghiqebjklrfcmno
1946 if func is None: 1pdaghiqebjklrfcmno
1947 return dec 1pdaghiqebjklrfcmno
1948 else:
1949 return dec(func) 1pdaghiqebjklrfcmno