Coverage for pydantic/fields.py: 99.02%
448 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-26 07:51 +0000
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-26 07:51 +0000
1"""Defining fields on models."""
3from __future__ import annotations as _annotations 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
5import dataclasses 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
6import inspect 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
7import sys 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
8import typing 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
9from collections.abc import Mapping 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
10from copy import copy 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
11from dataclasses import Field as DataclassField 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
12from functools import cached_property 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
13from typing import Annotated, Any, Callable, ClassVar, Literal, TypeVar, cast, overload 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
14from warnings import warn 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
16import annotated_types 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
17import typing_extensions 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
18from pydantic_core import PydanticUndefined 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
19from typing_extensions import TypeAlias, Unpack, deprecated 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
20from typing_inspection import typing_objects 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
21from typing_inspection.introspection import UNKNOWN, AnnotationSource, ForbiddenQualifier, Qualifier, inspect_annotation 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
23from . import types 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
24from ._internal import _decorators, _fields, _generics, _internal_dataclass, _repr, _typing_extra, _utils 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
25from ._internal._namespace_utils import GlobalsNamespace, MappingNamespace 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
26from .aliases import AliasChoices, AliasPath 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
27from .config import JsonDict 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
28from .errors import PydanticForbiddenQualifier, PydanticUserError 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
29from .json_schema import PydanticJsonSchemaWarning 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
30from .warnings import PydanticDeprecatedSince20 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
32if typing.TYPE_CHECKING: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
33 from ._internal._repr import ReprArgs 1l
34else:
35 # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
36 # and https://youtrack.jetbrains.com/issue/PY-51428
37 DeprecationWarning = PydanticDeprecatedSince20 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
39__all__ = 'Field', 'PrivateAttr', 'computed_field' 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
42_Unset: Any = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
44if sys.version_info >= (3, 13): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
45 import warnings 1abcdefJghi
47 Deprecated: TypeAlias = warnings.deprecated | deprecated 1abcdefJghi
48else:
49 Deprecated: TypeAlias = deprecated 1rstuvwjkqlxyzABCmnNOPKLMDEFGHIop
52class _FromFieldInfoInputs(typing_extensions.TypedDict, total=False): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
53 """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.from_field`."""
55 # TODO PEP 747: use TypeForm:
56 annotation: type[Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
57 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
58 alias: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
59 alias_priority: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
60 validation_alias: str | AliasPath | AliasChoices | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
61 serialization_alias: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
62 title: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
63 field_title_generator: Callable[[str, FieldInfo], str] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
64 description: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
65 examples: list[Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
66 exclude: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
67 gt: annotated_types.SupportsGt | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
68 ge: annotated_types.SupportsGe | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
69 lt: annotated_types.SupportsLt | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
70 le: annotated_types.SupportsLe | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
71 multiple_of: float | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
72 strict: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
73 min_length: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
74 max_length: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
75 pattern: str | typing.Pattern[str] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
76 allow_inf_nan: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
77 max_digits: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
78 decimal_places: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
79 union_mode: Literal['smart', 'left_to_right'] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
80 discriminator: str | types.Discriminator | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
81 deprecated: Deprecated | str | bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
82 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
83 frozen: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
84 validate_default: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
85 repr: bool 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
86 init: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
87 init_var: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
88 kw_only: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
89 coerce_numbers_to_str: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
90 fail_fast: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
93class _FieldInfoInputs(_FromFieldInfoInputs, total=False): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
94 """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.__init__`."""
96 default: Any 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
99class FieldInfo(_repr.Representation): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
100 """This class holds information about a field.
102 `FieldInfo` is used for any field definition regardless of whether the [`Field()`][pydantic.fields.Field]
103 function is explicitly used.
105 !!! warning
106 You generally shouldn't be creating `FieldInfo` directly, you'll only need to use it when accessing
107 [`BaseModel`][pydantic.main.BaseModel] `.model_fields` internals.
109 Attributes:
110 annotation: The type annotation of the field.
111 default: The default value of the field.
112 default_factory: A callable to generate the default value. The callable can either take 0 arguments
113 (in which case it is called as is) or a single argument containing the already validated data.
114 alias: The alias name of the field.
115 alias_priority: The priority of the field's alias.
116 validation_alias: The validation alias of the field.
117 serialization_alias: The serialization alias of the field.
118 title: The title of the field.
119 field_title_generator: A callable that takes a field name and returns title for it.
120 description: The description of the field.
121 examples: List of examples of the field.
122 exclude: Whether to exclude the field from the model serialization.
123 discriminator: Field name or Discriminator for discriminating the type in a tagged union.
124 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
125 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
126 json_schema_extra: A dict or callable to provide extra JSON schema properties.
127 frozen: Whether the field is frozen.
128 validate_default: Whether to validate the default value of the field.
129 repr: Whether to include the field in representation of the model.
130 init: Whether the field should be included in the constructor of the dataclass.
131 init_var: Whether the field should _only_ be included in the constructor of the dataclass, and not stored.
132 kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
133 metadata: List of metadata constraints.
134 """
136 annotation: type[Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
137 default: Any 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
138 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
139 alias: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
140 alias_priority: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
141 validation_alias: str | AliasPath | AliasChoices | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
142 serialization_alias: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
143 title: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
144 field_title_generator: Callable[[str, FieldInfo], str] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
145 description: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
146 examples: list[Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
147 exclude: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
148 discriminator: str | types.Discriminator | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
149 deprecated: Deprecated | str | bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
150 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
151 frozen: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
152 validate_default: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
153 repr: bool 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
154 init: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
155 init_var: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
156 kw_only: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
157 metadata: list[Any] 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
159 __slots__ = ( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
160 'annotation',
161 'default',
162 'default_factory',
163 'alias',
164 'alias_priority',
165 'validation_alias',
166 'serialization_alias',
167 'title',
168 'field_title_generator',
169 'description',
170 'examples',
171 'exclude',
172 'discriminator',
173 'deprecated',
174 'json_schema_extra',
175 'frozen',
176 'validate_default',
177 'repr',
178 'init',
179 'init_var',
180 'kw_only',
181 'metadata',
182 '_attributes_set',
183 '_qualifiers',
184 '_complete',
185 '_original_assignment',
186 '_original_annotation',
187 )
189 # used to convert kwargs to metadata/constraints,
190 # None has a special meaning - these items are collected into a `PydanticGeneralMetadata`
191 metadata_lookup: ClassVar[dict[str, typing.Callable[[Any], Any] | None]] = { 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
192 'strict': types.Strict,
193 'gt': annotated_types.Gt,
194 'ge': annotated_types.Ge,
195 'lt': annotated_types.Lt,
196 'le': annotated_types.Le,
197 'multiple_of': annotated_types.MultipleOf,
198 'min_length': annotated_types.MinLen,
199 'max_length': annotated_types.MaxLen,
200 'pattern': None,
201 'allow_inf_nan': None,
202 'max_digits': None,
203 'decimal_places': None,
204 'union_mode': None,
205 'coerce_numbers_to_str': None,
206 'fail_fast': types.FailFast,
207 }
209 def __init__(self, **kwargs: Unpack[_FieldInfoInputs]) -> None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
210 """This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
211 or one of the constructor classmethods.
213 See the signature of `pydantic.fields.Field` for more details about the expected arguments.
214 """
215 self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset} 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
216 kwargs = {k: _DefaultValues.get(k) if v is _Unset else v for k, v in kwargs.items()} # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
217 self.annotation = kwargs.get('annotation') 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
219 default = kwargs.pop('default', PydanticUndefined) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
220 if default is Ellipsis: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
221 self.default = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
222 self._attributes_set.pop('default', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
223 else:
224 self.default = default 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
226 self.default_factory = kwargs.pop('default_factory', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
228 if self.default is not PydanticUndefined and self.default_factory is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
229 raise TypeError('cannot specify both default and default_factory') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
231 self.alias = kwargs.pop('alias', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
232 self.validation_alias = kwargs.pop('validation_alias', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
233 self.serialization_alias = kwargs.pop('serialization_alias', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
234 alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias)) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
235 self.alias_priority = kwargs.pop('alias_priority', None) or 2 if alias_is_set else None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
236 self.title = kwargs.pop('title', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
237 self.field_title_generator = kwargs.pop('field_title_generator', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
238 self.description = kwargs.pop('description', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
239 self.examples = kwargs.pop('examples', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
240 self.exclude = kwargs.pop('exclude', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
241 self.discriminator = kwargs.pop('discriminator', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
242 # For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden
243 self.deprecated = kwargs.pop('deprecated', getattr(self, 'deprecated', None)) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
244 self.repr = kwargs.pop('repr', True) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
245 self.json_schema_extra = kwargs.pop('json_schema_extra', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
246 self.validate_default = kwargs.pop('validate_default', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
247 self.frozen = kwargs.pop('frozen', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
248 # currently only used on dataclasses
249 self.init = kwargs.pop('init', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
250 self.init_var = kwargs.pop('init_var', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
251 self.kw_only = kwargs.pop('kw_only', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
253 self.metadata = self._collect_metadata(kwargs) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
255 # Private attributes:
256 self._qualifiers: set[Qualifier] = set() 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
257 # Used to rebuild FieldInfo instances:
258 self._complete = True 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
259 self._original_annotation: Any = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
260 self._original_assignment: Any = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
262 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
263 def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
264 """Create a new `FieldInfo` object with the `Field` function.
266 Args:
267 default: The default value for the field. Defaults to Undefined.
268 **kwargs: Additional arguments dictionary.
270 Raises:
271 TypeError: If 'annotation' is passed as a keyword argument.
273 Returns:
274 A new FieldInfo object with the given parameters.
276 Example:
277 This is how you can create a field with default value like this:
279 ```python
280 import pydantic
282 class MyModel(pydantic.BaseModel):
283 foo: int = pydantic.Field(4)
284 ```
285 """
286 if 'annotation' in kwargs: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
287 raise TypeError('"annotation" is not permitted as a Field keyword argument') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
288 return FieldInfo(default=default, **kwargs) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
290 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
291 def from_annotation(annotation: type[Any], *, _source: AnnotationSource = AnnotationSource.ANY) -> FieldInfo: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
292 """Creates a `FieldInfo` instance from a bare annotation.
294 This function is used internally to create a `FieldInfo` from a bare annotation like this:
296 ```python
297 import pydantic
299 class MyModel(pydantic.BaseModel):
300 foo: int # <-- like this
301 ```
303 We also account for the case where the annotation can be an instance of `Annotated` and where
304 one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
306 ```python
307 from typing import Annotated
309 import annotated_types
311 import pydantic
313 class MyModel(pydantic.BaseModel):
314 foo: Annotated[int, annotated_types.Gt(42)]
315 bar: Annotated[int, pydantic.Field(gt=42)]
316 ```
318 Args:
319 annotation: An annotation object.
321 Returns:
322 An instance of the field metadata.
323 """
324 try: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
325 inspected_ann = inspect_annotation( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
326 annotation,
327 annotation_source=_source,
328 unpack_type_aliases='skip',
329 )
330 except ForbiddenQualifier as e: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
331 raise PydanticForbiddenQualifier(e.qualifier, annotation) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
333 # TODO check for classvar and error?
335 # No assigned value, this happens when using a bare `Final` qualifier (also for other
336 # qualifiers, but they shouldn't appear here). In this case we infer the type as `Any`
337 # because we don't have any assigned value.
338 type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
339 final = 'final' in inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
340 metadata = inspected_ann.metadata 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
342 if not metadata: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
343 # No metadata, e.g. `field: int`, or `field: Final[str]`:
344 field_info = FieldInfo(annotation=type_expr, frozen=final or None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
345 field_info._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
346 return field_info 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
348 # With metadata, e.g. `field: Annotated[int, Field(...), Gt(1)]`:
349 field_info_annotations = [a for a in metadata if isinstance(a, FieldInfo)] 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
350 field_info = FieldInfo.merge_field_infos(*field_info_annotations, annotation=type_expr) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
352 new_field_info = copy(field_info) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
353 new_field_info.annotation = type_expr 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
354 new_field_info.frozen = final or field_info.frozen 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
355 field_metadata: list[Any] = [] 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
356 for a in metadata: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
357 if typing_objects.is_deprecated(a): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
358 new_field_info.deprecated = a.message 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
359 elif not isinstance(a, FieldInfo): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
360 field_metadata.append(a) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
361 else:
362 field_metadata.extend(a.metadata) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
363 new_field_info.metadata = field_metadata 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
364 new_field_info._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
365 return new_field_info 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
367 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
368 def from_annotated_attribute( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
369 annotation: type[Any], default: Any, *, _source: AnnotationSource = AnnotationSource.ANY
370 ) -> FieldInfo:
371 """Create `FieldInfo` from an annotation with a default value.
373 This is used in cases like the following:
375 ```python
376 from typing import Annotated
378 import annotated_types
380 import pydantic
382 class MyModel(pydantic.BaseModel):
383 foo: int = 4 # <-- like this
384 bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
385 spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
386 ```
388 Args:
389 annotation: The type annotation of the field.
390 default: The default value of the field.
392 Returns:
393 A field object with the passed values.
394 """
395 if annotation is default: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
396 raise PydanticUserError( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
397 'Error when building FieldInfo from annotated attribute. '
398 "Make sure you don't have any field name clashing with a type annotation.",
399 code='unevaluable-type-annotation',
400 )
402 try: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
403 inspected_ann = inspect_annotation( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
404 annotation,
405 annotation_source=_source,
406 unpack_type_aliases='skip',
407 )
408 except ForbiddenQualifier as e: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
409 raise PydanticForbiddenQualifier(e.qualifier, annotation) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
411 # TODO check for classvar and error?
413 # TODO infer from the default, this can be done in v3 once we treat final fields with
414 # a default as proper fields and not class variables:
415 type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
416 final = 'final' in inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
417 metadata = inspected_ann.metadata 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
419 if isinstance(default, FieldInfo): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
420 # e.g. `field: int = Field(...)`
421 default.annotation = type_expr 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
422 default.metadata += metadata 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
423 merged_default = FieldInfo.merge_field_infos( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
424 *[x for x in metadata if isinstance(x, FieldInfo)],
425 default,
426 annotation=default.annotation,
427 )
428 merged_default.frozen = final or merged_default.frozen 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
429 merged_default._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
430 return merged_default 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
432 if isinstance(default, dataclasses.Field): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
433 # `collect_dataclass_fields()` passes the dataclass Field as a default.
434 pydantic_field = FieldInfo._from_dataclass_field(default) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
435 pydantic_field.annotation = type_expr 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
436 pydantic_field.metadata += metadata 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
437 pydantic_field = FieldInfo.merge_field_infos( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
438 *[x for x in metadata if isinstance(x, FieldInfo)],
439 pydantic_field,
440 annotation=pydantic_field.annotation,
441 )
442 pydantic_field.frozen = final or pydantic_field.frozen 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
443 pydantic_field.init_var = 'init_var' in inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
444 pydantic_field.init = getattr(default, 'init', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
445 pydantic_field.kw_only = getattr(default, 'kw_only', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
446 pydantic_field._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
447 return pydantic_field 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
449 if not metadata: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
450 # No metadata, e.g. `field: int = ...`, or `field: Final[str] = ...`:
451 field_info = FieldInfo(annotation=type_expr, default=default, frozen=final or None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
452 field_info._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
453 return field_info 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
455 # With metadata, e.g. `field: Annotated[int, Field(...), Gt(1)] = ...`:
456 field_infos = [a for a in metadata if isinstance(a, FieldInfo)] 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
457 field_info = FieldInfo.merge_field_infos(*field_infos, annotation=type_expr, default=default) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
458 field_metadata: list[Any] = [] 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
459 for a in metadata: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
460 if typing_objects.is_deprecated(a): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
461 field_info.deprecated = a.message 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
462 elif not isinstance(a, FieldInfo): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
463 field_metadata.append(a) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
464 else:
465 field_metadata.extend(a.metadata) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
466 field_info.metadata = field_metadata 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
467 field_info._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
468 return field_info 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
470 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
471 def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
472 """Merge `FieldInfo` instances keeping only explicitly set attributes.
474 Later `FieldInfo` instances override earlier ones.
476 Returns:
477 FieldInfo: A merged FieldInfo instance.
478 """
479 if len(field_infos) == 1: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
480 # No merging necessary, but we still need to make a copy and apply the overrides
481 field_info = copy(field_infos[0]) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
482 field_info._attributes_set.update(overrides) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
484 default_override = overrides.pop('default', PydanticUndefined) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
485 if default_override is Ellipsis: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
486 default_override = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
487 if default_override is not PydanticUndefined: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
488 field_info.default = default_override 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
490 for k, v in overrides.items(): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
491 setattr(field_info, k, v) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
492 return field_info # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
494 merged_field_info_kwargs: dict[str, Any] = {} 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
495 metadata = {} 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
496 for field_info in field_infos: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
497 attributes_set = field_info._attributes_set.copy() 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
499 try: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
500 json_schema_extra = attributes_set.pop('json_schema_extra') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
501 existing_json_schema_extra = merged_field_info_kwargs.get('json_schema_extra') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
503 if existing_json_schema_extra is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
504 merged_field_info_kwargs['json_schema_extra'] = json_schema_extra 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
505 if isinstance(existing_json_schema_extra, dict): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
506 if isinstance(json_schema_extra, dict): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
507 merged_field_info_kwargs['json_schema_extra'] = { 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
508 **existing_json_schema_extra,
509 **json_schema_extra,
510 }
511 if callable(json_schema_extra): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
512 warn( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
513 'Composing `dict` and `callable` type `json_schema_extra` is not supported.'
514 'The `callable` type is being ignored.'
515 "If you'd like support for this behavior, please open an issue on pydantic.",
516 PydanticJsonSchemaWarning,
517 )
518 elif callable(json_schema_extra): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
519 # if ever there's a case of a callable, we'll just keep the last json schema extra spec
520 merged_field_info_kwargs['json_schema_extra'] = json_schema_extra 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
521 except KeyError: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
522 pass 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
524 # later FieldInfo instances override everything except json_schema_extra from earlier FieldInfo instances
525 merged_field_info_kwargs.update(attributes_set) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
527 for x in field_info.metadata: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
528 if not isinstance(x, FieldInfo): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
529 metadata[type(x)] = x 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
531 merged_field_info_kwargs.update(overrides) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
532 field_info = FieldInfo(**merged_field_info_kwargs) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
533 field_info.metadata = list(metadata.values()) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
534 return field_info 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
536 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
537 def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
538 """Return a new `FieldInfo` instance from a `dataclasses.Field` instance.
540 Args:
541 dc_field: The `dataclasses.Field` instance to convert.
543 Returns:
544 The corresponding `FieldInfo` instance.
546 Raises:
547 TypeError: If any of the `FieldInfo` kwargs does not match the `dataclass.Field` kwargs.
548 """
549 default = dc_field.default 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
550 if default is dataclasses.MISSING: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
551 default = _Unset 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
553 if dc_field.default_factory is dataclasses.MISSING: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
554 default_factory = _Unset 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
555 else:
556 default_factory = dc_field.default_factory 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
558 # use the `Field` function so in correct kwargs raise the correct `TypeError`
559 dc_field_metadata = {k: v for k, v in dc_field.metadata.items() if k in _FIELD_ARG_NAMES} 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
560 return Field(default=default, default_factory=default_factory, repr=dc_field.repr, **dc_field_metadata) # pyright: ignore[reportCallIssue] 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
562 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
563 def _collect_metadata(kwargs: dict[str, Any]) -> list[Any]: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
564 """Collect annotations from kwargs.
566 Args:
567 kwargs: Keyword arguments passed to the function.
569 Returns:
570 A list of metadata objects - a combination of `annotated_types.BaseMetadata` and
571 `PydanticMetadata`.
572 """
573 metadata: list[Any] = [] 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
574 general_metadata = {} 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
575 for key, value in list(kwargs.items()): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
576 try: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
577 marker = FieldInfo.metadata_lookup[key] 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
578 except KeyError: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
579 continue 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
581 del kwargs[key] 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
582 if value is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
583 if marker is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
584 general_metadata[key] = value 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
585 else:
586 metadata.append(marker(value)) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
587 if general_metadata: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
588 metadata.append(_fields.pydantic_general_metadata(**general_metadata)) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
589 return metadata 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
591 @property 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
592 def deprecation_message(self) -> str | None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
593 """The deprecation message to be emitted, or `None` if not set."""
594 if self.deprecated is None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
595 return None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
596 if isinstance(self.deprecated, bool): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
597 return 'deprecated' if self.deprecated else None 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
598 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
600 @property 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
601 def default_factory_takes_validated_data(self) -> bool | None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
602 """Whether the provided default factory callable has a validated data parameter.
604 Returns `None` if no default factory is set.
605 """
606 if self.default_factory is not None: 606 ↛ exitline 606 didn't return from function 'default_factory_takes_validated_data' because the condition on line 606 was always true1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
607 return _fields.takes_validated_data_argument(self.default_factory) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
609 @overload 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
610 def get_default( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
611 self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
612 ) -> Any: ... 1jkabcqlmndefKLMJopghi
614 @overload 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
615 def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ... 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
617 def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
618 """Get the default value.
620 We expose an option for whether to call the default_factory (if present), as calling it may
621 result in side effects that we want to avoid. However, there are times when it really should
622 be called (namely, when instantiating a model via `model_construct`).
624 Args:
625 call_default_factory: Whether to call the default factory or not.
626 validated_data: The already validated data to be passed to the default factory.
628 Returns:
629 The default value, calling the default factory if requested or `None` if not set.
630 """
631 if self.default_factory is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
632 return _utils.smart_deepcopy(self.default) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
633 elif call_default_factory: 633 ↛ 645line 633 didn't jump to line 645 because the condition on line 633 was always true1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
634 if self.default_factory_takes_validated_data: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
635 fac = cast('Callable[[dict[str, Any]], Any]', self.default_factory) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
636 if validated_data is None: 636 ↛ 637line 636 didn't jump to line 637 because the condition on line 636 was never true1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
637 raise ValueError(
638 "The default factory requires the 'validated_data' argument, which was not provided when calling 'get_default'."
639 )
640 return fac(validated_data) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
641 else:
642 fac = cast('Callable[[], Any]', self.default_factory) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
643 return fac() 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
644 else:
645 return None
647 def is_required(self) -> bool: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
648 """Check if the field is required (i.e., does not have a default value or factory).
650 Returns:
651 `True` if the field is required, `False` otherwise.
652 """
653 return self.default is PydanticUndefined and self.default_factory is None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
655 def rebuild_annotation(self) -> Any: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
656 """Attempts to rebuild the original annotation for use in function signatures.
658 If metadata is present, it adds it to the original annotation using
659 `Annotated`. Otherwise, it returns the original annotation as-is.
661 Note that because the metadata has been flattened, the original annotation
662 may not be reconstructed exactly as originally provided, e.g. if the original
663 type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
665 Returns:
666 The rebuilt annotation.
667 """
668 if not self.metadata: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
669 return self.annotation 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
670 else:
671 # Annotated arguments must be a tuple
672 return Annotated[(self.annotation, *self.metadata)] # type: ignore 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
674 def apply_typevars_map( 1rstuvwjkabcxyzABCmndefNOPKLMJDEFGHIopghi
675 self,
676 typevars_map: Mapping[TypeVar, Any] | None,
677 globalns: GlobalsNamespace | None = None,
678 localns: MappingNamespace | None = None,
679 ) -> None:
680 """Apply a `typevars_map` to the annotation.
682 This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
684 This method applies the `typevars_map` to the annotation in place.
686 Args:
687 typevars_map: A dictionary mapping type variables to their concrete types.
688 globalns: The globals namespace to use during type annotation evaluation.
689 localns: The locals namespace to use during type annotation evaluation.
691 See Also:
692 pydantic._internal._generics.replace_types is used for replacing the typevars with
693 their concrete types.
694 """
695 annotation, _ = _typing_extra.try_eval_type(self.annotation, globalns, localns) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
696 self.annotation = _generics.replace_types(annotation, typevars_map) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
698 def __repr_args__(self) -> ReprArgs: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
699 yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation)) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
700 yield 'required', self.is_required() 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
702 for s in self.__slots__: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
703 # TODO: properly make use of the protocol (https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol)
704 # By yielding a three-tuple:
705 if s in ( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
706 'annotation',
707 '_attributes_set',
708 '_qualifiers',
709 '_complete',
710 '_original_assignment',
711 '_original_annotation',
712 ):
713 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
714 elif s == 'metadata' and not self.metadata: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
715 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
716 elif s == 'repr' and self.repr is True: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
717 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
718 if s == 'frozen' and self.frozen is False: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
719 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
720 if s == 'validation_alias' and self.validation_alias == self.alias: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
721 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
722 if s == 'serialization_alias' and self.serialization_alias == self.alias: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
723 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
724 if s == 'default' and self.default is not PydanticUndefined: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
725 yield 'default', self.default 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
726 elif s == 'default_factory' and self.default_factory is not None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
727 yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory)) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
728 else:
729 value = getattr(self, s) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
730 if value is not None and value is not PydanticUndefined: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
731 yield s, value 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
734class _EmptyKwargs(typing_extensions.TypedDict): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
735 """This class exists solely to ensure that type checking warns about passing `**extra` in `Field`."""
738_DefaultValues = { 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
739 'default': ...,
740 'default_factory': None,
741 'alias': None,
742 'alias_priority': None,
743 'validation_alias': None,
744 'serialization_alias': None,
745 'title': None,
746 'description': None,
747 'examples': None,
748 'exclude': None,
749 'discriminator': None,
750 'json_schema_extra': None,
751 'frozen': None,
752 'validate_default': None,
753 'repr': True,
754 'init': None,
755 'init_var': None,
756 'kw_only': None,
757 'pattern': None,
758 'strict': None,
759 'gt': None,
760 'ge': None,
761 'lt': None,
762 'le': None,
763 'multiple_of': None,
764 'allow_inf_nan': None,
765 'max_digits': None,
766 'decimal_places': None,
767 'min_length': None,
768 'max_length': None,
769 'coerce_numbers_to_str': None,
770}
773_T = TypeVar('_T') 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
776# NOTE: Actual return type is 'FieldInfo', but we want to help type checkers
777# to understand the magic that happens at runtime with the following overloads:
778@overload # type hint the return value as `Any` to avoid type checking regressions when using `...`. 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
779def Field( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
780 default: ellipsis, # noqa: F821 # TODO: use `_typing_extra.EllipsisType` when we drop Py3.9 1jkabcqlmndefKLMJopghi
781 *,
782 alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
783 alias_priority: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
784 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
785 serialization_alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
786 title: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
787 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
788 description: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
789 examples: list[Any] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
790 exclude: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
791 discriminator: str | types.Discriminator | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
792 deprecated: Deprecated | str | bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
793 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
794 frozen: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
795 validate_default: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
796 repr: bool = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
797 init: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
798 init_var: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
799 kw_only: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
800 pattern: str | typing.Pattern[str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
801 strict: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
802 coerce_numbers_to_str: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
803 gt: annotated_types.SupportsGt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
804 ge: annotated_types.SupportsGe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
805 lt: annotated_types.SupportsLt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
806 le: annotated_types.SupportsLe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
807 multiple_of: float | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
808 allow_inf_nan: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
809 max_digits: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
810 decimal_places: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
811 min_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
812 max_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
813 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
814 fail_fast: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
815 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefKLMJopghi
816) -> Any: ... 1jkabcqlmndefKLMJopghi
817@overload # `default` argument set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
818def Field( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
819 default: _T, 1jkabcqlmndefKLMJopghi
820 *,
821 alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
822 alias_priority: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
823 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
824 serialization_alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
825 title: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
826 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
827 description: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
828 examples: list[Any] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
829 exclude: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
830 discriminator: str | types.Discriminator | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
831 deprecated: Deprecated | str | bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
832 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
833 frozen: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
834 validate_default: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
835 repr: bool = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
836 init: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
837 init_var: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
838 kw_only: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
839 pattern: str | typing.Pattern[str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
840 strict: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
841 coerce_numbers_to_str: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
842 gt: annotated_types.SupportsGt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
843 ge: annotated_types.SupportsGe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
844 lt: annotated_types.SupportsLt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
845 le: annotated_types.SupportsLe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
846 multiple_of: float | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
847 allow_inf_nan: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
848 max_digits: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
849 decimal_places: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
850 min_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
851 max_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
852 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
853 fail_fast: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
854 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefKLMJopghi
855) -> _T: ... 1jkabcqlmndefKLMJopghi
856@overload # `default_factory` argument set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
857def Field( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
858 *,
859 default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T], 1jkabcqlmndefKLMJopghi
860 alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
861 alias_priority: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
862 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
863 serialization_alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
864 title: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
865 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
866 description: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
867 examples: list[Any] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
868 exclude: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
869 discriminator: str | types.Discriminator | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
870 deprecated: Deprecated | str | bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
871 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
872 frozen: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
873 validate_default: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
874 repr: bool = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
875 init: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
876 init_var: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
877 kw_only: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
878 pattern: str | typing.Pattern[str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
879 strict: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
880 coerce_numbers_to_str: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
881 gt: annotated_types.SupportsGt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
882 ge: annotated_types.SupportsGe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
883 lt: annotated_types.SupportsLt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
884 le: annotated_types.SupportsLe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
885 multiple_of: float | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
886 allow_inf_nan: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
887 max_digits: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
888 decimal_places: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
889 min_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
890 max_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
891 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
892 fail_fast: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
893 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefKLMJopghi
894) -> _T: ... 1jkabcqlmndefKLMJopghi
895@overload 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
896def Field( # No default set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
897 *,
898 alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
899 alias_priority: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
900 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
901 serialization_alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
902 title: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
903 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
904 description: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
905 examples: list[Any] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
906 exclude: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
907 discriminator: str | types.Discriminator | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
908 deprecated: Deprecated | str | bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
909 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
910 frozen: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
911 validate_default: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
912 repr: bool = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
913 init: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
914 init_var: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
915 kw_only: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
916 pattern: str | typing.Pattern[str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
917 strict: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
918 coerce_numbers_to_str: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
919 gt: annotated_types.SupportsGt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
920 ge: annotated_types.SupportsGe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
921 lt: annotated_types.SupportsLt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
922 le: annotated_types.SupportsLe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
923 multiple_of: float | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
924 allow_inf_nan: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
925 max_digits: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
926 decimal_places: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
927 min_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
928 max_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
929 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
930 fail_fast: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
931 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefKLMJopghi
932) -> Any: ... 1jkabcqlmndefKLMJopghi
933def Field( # noqa: C901 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
934 default: Any = PydanticUndefined,
935 *,
936 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = _Unset,
937 alias: str | None = _Unset,
938 alias_priority: int | None = _Unset,
939 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
940 serialization_alias: str | None = _Unset,
941 title: str | None = _Unset,
942 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
943 description: str | None = _Unset,
944 examples: list[Any] | None = _Unset,
945 exclude: bool | None = _Unset,
946 discriminator: str | types.Discriminator | None = _Unset,
947 deprecated: Deprecated | str | bool | None = _Unset,
948 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
949 frozen: bool | None = _Unset,
950 validate_default: bool | None = _Unset,
951 repr: bool = _Unset,
952 init: bool | None = _Unset,
953 init_var: bool | None = _Unset,
954 kw_only: bool | None = _Unset,
955 pattern: str | typing.Pattern[str] | None = _Unset,
956 strict: bool | None = _Unset,
957 coerce_numbers_to_str: bool | None = _Unset,
958 gt: annotated_types.SupportsGt | None = _Unset,
959 ge: annotated_types.SupportsGe | None = _Unset,
960 lt: annotated_types.SupportsLt | None = _Unset,
961 le: annotated_types.SupportsLe | None = _Unset,
962 multiple_of: float | None = _Unset,
963 allow_inf_nan: bool | None = _Unset,
964 max_digits: int | None = _Unset,
965 decimal_places: int | None = _Unset,
966 min_length: int | None = _Unset,
967 max_length: int | None = _Unset,
968 union_mode: Literal['smart', 'left_to_right'] = _Unset,
969 fail_fast: bool | None = _Unset,
970 **extra: Unpack[_EmptyKwargs],
971) -> Any:
972 """!!! abstract "Usage Documentation"
973 [Fields](../concepts/fields.md)
975 Create a field for objects that can be configured.
977 Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
978 apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`.
980 Note:
981 - Any `_Unset` objects will be replaced by the corresponding value defined in the `_DefaultValues` dictionary. If a key for the `_Unset` object is not found in the `_DefaultValues` dictionary, it will default to `None`
983 Args:
984 default: Default value if the field is not set.
985 default_factory: A callable to generate the default value. The callable can either take 0 arguments
986 (in which case it is called as is) or a single argument containing the already validated data.
987 alias: The name to use for the attribute when validating or serializing by alias.
988 This is often used for things like converting between snake and camel case.
989 alias_priority: Priority of the alias. This affects whether an alias generator is used.
990 validation_alias: Like `alias`, but only affects validation, not serialization.
991 serialization_alias: Like `alias`, but only affects serialization, not validation.
992 title: Human-readable title.
993 field_title_generator: A callable that takes a field name and returns title for it.
994 description: Human-readable description.
995 examples: Example values for this field.
996 exclude: Whether to exclude the field from the model serialization.
997 discriminator: Field name or Discriminator for discriminating the type in a tagged union.
998 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
999 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
1000 json_schema_extra: A dict or callable to provide extra JSON schema properties.
1001 frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.
1002 validate_default: If `True`, apply validation to the default value every time you create an instance.
1003 Otherwise, for performance reasons, the default value of the field is trusted and not validated.
1004 repr: A boolean indicating whether to include the field in the `__repr__` output.
1005 init: Whether the field should be included in the constructor of the dataclass.
1006 (Only applies to dataclasses.)
1007 init_var: Whether the field should _only_ be included in the constructor of the dataclass.
1008 (Only applies to dataclasses.)
1009 kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
1010 (Only applies to dataclasses.)
1011 coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
1012 strict: If `True`, strict validation is applied to the field.
1013 See [Strict Mode](../concepts/strict_mode.md) for details.
1014 gt: Greater than. If set, value must be greater than this. Only applicable to numbers.
1015 ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.
1016 lt: Less than. If set, value must be less than this. Only applicable to numbers.
1017 le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.
1018 multiple_of: Value must be a multiple of this. Only applicable to numbers.
1019 min_length: Minimum length for iterables.
1020 max_length: Maximum length for iterables.
1021 pattern: Pattern for strings (a regular expression).
1022 allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to float and [`Decimal`][decimal.Decimal] numbers.
1023 max_digits: Maximum number of allow digits for strings.
1024 decimal_places: Maximum number of decimal places allowed for numbers.
1025 union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`.
1026 See [Union Mode](../concepts/unions.md#union-modes) for details.
1027 fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected.
1028 This option can be applied only to iterable types (list, tuple, set, and frozenset).
1029 extra: (Deprecated) Extra fields that will be included in the JSON schema.
1031 !!! warning Deprecated
1032 The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
1034 Returns:
1035 A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on
1036 type-annotated fields without causing a type error.
1037 """
1038 # Check deprecated and removed params from V1. This logic should eventually be removed.
1039 const = extra.pop('const', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1040 if const is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1041 raise PydanticUserError('`const` is removed, use `Literal` instead', code='removed-kwargs') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1043 min_items = extra.pop('min_items', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1044 if min_items is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1045 warn('`min_items` is deprecated and will be removed, use `min_length` instead', DeprecationWarning) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1046 if min_length in (None, _Unset): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1047 min_length = min_items # type: ignore 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1049 max_items = extra.pop('max_items', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1050 if max_items is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1051 warn('`max_items` is deprecated and will be removed, use `max_length` instead', DeprecationWarning) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1052 if max_length in (None, _Unset): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1053 max_length = max_items # type: ignore 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1055 unique_items = extra.pop('unique_items', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1056 if unique_items is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1057 raise PydanticUserError( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1058 (
1059 '`unique_items` is removed, use `Set` instead'
1060 '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)'
1061 ),
1062 code='removed-kwargs',
1063 )
1065 allow_mutation = extra.pop('allow_mutation', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1066 if allow_mutation is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1067 warn('`allow_mutation` is deprecated and will be removed. use `frozen` instead', DeprecationWarning) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1068 if allow_mutation is False: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1069 frozen = True 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1071 regex = extra.pop('regex', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1072 if regex is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1073 raise PydanticUserError('`regex` is removed. use `pattern` instead', code='removed-kwargs') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1075 if extra: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1076 warn( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1077 'Using extra keyword arguments on `Field` is deprecated and will be removed.'
1078 ' Use `json_schema_extra` instead.'
1079 f' (Extra keys: {", ".join(k.__repr__() for k in extra.keys())})',
1080 DeprecationWarning,
1081 )
1082 if not json_schema_extra or json_schema_extra is _Unset: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1083 json_schema_extra = extra # type: ignore 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1085 if ( 1rstuvwqlxyzABCNOPDEFGHI
1086 validation_alias
1087 and validation_alias is not _Unset
1088 and not isinstance(validation_alias, (str, AliasChoices, AliasPath))
1089 ):
1090 raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1092 if serialization_alias in (_Unset, None) and isinstance(alias, str): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1093 serialization_alias = alias 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1095 if validation_alias in (_Unset, None): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1096 validation_alias = alias 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1098 include = extra.pop('include', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1099 if include is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1100 warn('`include` is deprecated and does nothing. It will be removed, use `exclude` instead', DeprecationWarning) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1102 return FieldInfo.from_field( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1103 default,
1104 default_factory=default_factory,
1105 alias=alias,
1106 alias_priority=alias_priority,
1107 validation_alias=validation_alias,
1108 serialization_alias=serialization_alias,
1109 title=title,
1110 field_title_generator=field_title_generator,
1111 description=description,
1112 examples=examples,
1113 exclude=exclude,
1114 discriminator=discriminator,
1115 deprecated=deprecated,
1116 json_schema_extra=json_schema_extra,
1117 frozen=frozen,
1118 pattern=pattern,
1119 validate_default=validate_default,
1120 repr=repr,
1121 init=init,
1122 init_var=init_var,
1123 kw_only=kw_only,
1124 coerce_numbers_to_str=coerce_numbers_to_str,
1125 strict=strict,
1126 gt=gt,
1127 ge=ge,
1128 lt=lt,
1129 le=le,
1130 multiple_of=multiple_of,
1131 min_length=min_length,
1132 max_length=max_length,
1133 allow_inf_nan=allow_inf_nan,
1134 max_digits=max_digits,
1135 decimal_places=decimal_places,
1136 union_mode=union_mode,
1137 fail_fast=fail_fast,
1138 )
1141_FIELD_ARG_NAMES = set(inspect.signature(Field).parameters) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1142_FIELD_ARG_NAMES.remove('extra') # do not include the varkwargs parameter 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1145class ModelPrivateAttr(_repr.Representation): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1146 """A descriptor for private attributes in class models.
1148 !!! warning
1149 You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use
1150 `pydantic.fields.PrivateAttr`. (This is similar to `FieldInfo` vs. `Field`.)
1152 Attributes:
1153 default: The default value of the attribute if not provided.
1154 default_factory: A callable function that generates the default value of the
1155 attribute if not provided.
1156 """
1158 __slots__ = ('default', 'default_factory') 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1160 def __init__( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1161 self, default: Any = PydanticUndefined, *, default_factory: typing.Callable[[], Any] | None = None
1162 ) -> None:
1163 if default is Ellipsis: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1164 self.default = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1165 else:
1166 self.default = default 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1167 self.default_factory = default_factory 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1169 if not typing.TYPE_CHECKING: 1169 ↛ 1181line 1169 didn't jump to line 1181 because the condition on line 1169 was always true1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1170 # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
1172 def __getattr__(self, item: str) -> Any: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1173 """This function improves compatibility with custom descriptors by ensuring delegation happens
1174 as expected when the default value of a private attribute is a descriptor.
1175 """
1176 if item in {'__get__', '__set__', '__delete__'}: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1177 if hasattr(self.default, item): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1178 return getattr(self.default, item) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1179 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1181 def __set_name__(self, cls: type[Any], name: str) -> None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1182 """Preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487."""
1183 default = self.default 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1184 if default is PydanticUndefined: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1185 return 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1186 set_name = getattr(default, '__set_name__', None) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1187 if callable(set_name): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1188 set_name(cls, name) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1190 def get_default(self) -> Any: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1191 """Retrieve the default value of the object.
1193 If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object.
1195 If `self.default_factory` is not `None`, it will call `self.default_factory` and return the value returned.
1197 Returns:
1198 The default value of the object.
1199 """
1200 return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1202 def __eq__(self, other: Any) -> bool: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1203 return isinstance(other, self.__class__) and (self.default, self.default_factory) == ( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1204 other.default,
1205 other.default_factory,
1206 )
1209# NOTE: Actual return type is 'ModelPrivateAttr', but we want to help type checkers
1210# to understand the magic that happens at runtime.
1211@overload # `default` argument set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1212def PrivateAttr( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1213 default: _T, 1jkabcqlmndefKLMJopghi
1214 *,
1215 init: Literal[False] = False, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1216) -> _T: ... 1jkabcqlmndefKLMJopghi
1217@overload # `default_factory` argument set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1218def PrivateAttr( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1219 *,
1220 default_factory: Callable[[], _T], 1jkabcqlmndefKLMJopghi
1221 init: Literal[False] = False, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1222) -> _T: ... 1jkabcqlmndefKLMJopghi
1223@overload # No default set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1224def PrivateAttr( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1225 *,
1226 init: Literal[False] = False, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1227) -> Any: ... 1jkabcqlmndefKLMJopghi
1228def PrivateAttr( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1229 default: Any = PydanticUndefined,
1230 *,
1231 default_factory: Callable[[], Any] | None = None,
1232 init: Literal[False] = False,
1233) -> Any:
1234 """!!! abstract "Usage Documentation"
1235 [Private Model Attributes](../concepts/models.md#private-model-attributes)
1237 Indicates that an attribute is intended for private use and not handled during normal validation/serialization.
1239 Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner.
1241 Private attributes are stored in `__private_attributes__` on the model.
1243 Args:
1244 default: The attribute's default value. Defaults to Undefined.
1245 default_factory: Callable that will be
1246 called when a default value is needed for this attribute.
1247 If both `default` and `default_factory` are set, an error will be raised.
1248 init: Whether the attribute should be included in the constructor of the dataclass. Always `False`.
1250 Returns:
1251 An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class.
1253 Raises:
1254 ValueError: If both `default` and `default_factory` are set.
1255 """
1256 if default is not PydanticUndefined and default_factory is not None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1257 raise TypeError('cannot specify both default and default_factory') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1259 return ModelPrivateAttr( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1260 default,
1261 default_factory=default_factory,
1262 )
1265@dataclasses.dataclass(**_internal_dataclass.slots_true) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1266class ComputedFieldInfo: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1267 """A container for data from `@computed_field` so that we can access it while building the pydantic-core schema.
1269 Attributes:
1270 decorator_repr: A class variable representing the decorator string, '@computed_field'.
1271 wrapped_property: The wrapped computed field property.
1272 return_type: The type of the computed field property's return value.
1273 alias: The alias of the property to be used during serialization.
1274 alias_priority: The priority of the alias. This affects whether an alias generator is used.
1275 title: Title of the computed field to include in the serialization JSON schema.
1276 field_title_generator: A callable that takes a field name and returns title for it.
1277 description: Description of the computed field to include in the serialization JSON schema.
1278 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
1279 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
1280 examples: Example values of the computed field to include in the serialization JSON schema.
1281 json_schema_extra: A dict or callable to provide extra JSON schema properties.
1282 repr: A boolean indicating whether to include the field in the __repr__ output.
1283 """
1285 decorator_repr: ClassVar[str] = '@computed_field' 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1286 wrapped_property: property 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1287 return_type: Any 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1288 alias: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1289 alias_priority: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1290 title: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1291 field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1292 description: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1293 deprecated: Deprecated | str | bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1294 examples: list[Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1295 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1296 repr: bool 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1298 @property 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1299 def deprecation_message(self) -> str | None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1300 """The deprecation message to be emitted, or `None` if not set."""
1301 if self.deprecated is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1302 return None 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1303 if isinstance(self.deprecated, bool): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1304 return 'deprecated' if self.deprecated else None 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1305 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1308def _wrapped_property_is_private(property_: cached_property | property) -> bool: # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1309 """Returns true if provided property is private, False otherwise."""
1310 wrapped_name: str = '' 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1312 if isinstance(property_, property): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1313 wrapped_name = getattr(property_.fget, '__name__', '') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1314 elif isinstance(property_, cached_property): # type: ignore 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1315 wrapped_name = getattr(property_.func, '__name__', '') # type: ignore 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1317 return wrapped_name.startswith('_') and not wrapped_name.startswith('__') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1320# this should really be `property[T], cached_property[T]` but property is not generic unlike cached_property
1321# See https://github.com/python/typing/issues/985 and linked issues
1322PropertyT = typing.TypeVar('PropertyT') 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1325@typing.overload 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1326def computed_field(func: PropertyT, /) -> PropertyT: ... 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1329@typing.overload 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1330def computed_field( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1331 *,
1332 alias: str | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1333 alias_priority: int | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1334 title: str | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1335 field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1336 description: str | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1337 deprecated: Deprecated | str | bool | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1338 examples: list[Any] | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1339 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1340 repr: bool = True, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1341 return_type: Any = PydanticUndefined, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi
1342) -> typing.Callable[[PropertyT], PropertyT]: ... 1jkabcqlmndefKLMJopghi
1345def computed_field( 1rstuvwjkabcxyzABCmndefNOPKLMJDEFGHIopghi
1346 func: PropertyT | None = None,
1347 /,
1348 *,
1349 alias: str | None = None,
1350 alias_priority: int | None = None,
1351 title: str | None = None,
1352 field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None,
1353 description: str | None = None,
1354 deprecated: Deprecated | str | bool | None = None,
1355 examples: list[Any] | None = None,
1356 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None,
1357 repr: bool | None = None,
1358 return_type: Any = PydanticUndefined,
1359) -> PropertyT | typing.Callable[[PropertyT], PropertyT]:
1360 """!!! abstract "Usage Documentation"
1361 [The `computed_field` decorator](../concepts/fields.md#the-computed_field-decorator)
1363 Decorator to include `property` and `cached_property` when serializing models or dataclasses.
1365 This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.
1367 ```python
1368 from pydantic import BaseModel, computed_field
1370 class Rectangle(BaseModel):
1371 width: int
1372 length: int
1374 @computed_field
1375 @property
1376 def area(self) -> int:
1377 return self.width * self.length
1379 print(Rectangle(width=3, length=2).model_dump())
1380 #> {'width': 3, 'length': 2, 'area': 6}
1381 ```
1383 If applied to functions not yet decorated with `@property` or `@cached_property`, the function is
1384 automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE,
1385 and confuse static type checkers, thus explicit use of `@property` is recommended.
1387 !!! warning "Mypy Warning"
1388 Even with the `@property` or `@cached_property` applied to your function before `@computed_field`,
1389 mypy may throw a `Decorated property not supported` error.
1390 See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information.
1391 To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line.
1393 [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error.
1395 ```python
1396 import random
1398 from pydantic import BaseModel, computed_field
1400 class Square(BaseModel):
1401 width: float
1403 @computed_field
1404 def area(self) -> float: # converted to a `property` by `computed_field`
1405 return round(self.width**2, 2)
1407 @area.setter
1408 def area(self, new_area: float) -> None:
1409 self.width = new_area**0.5
1411 @computed_field(alias='the magic number', repr=False)
1412 def random_number(self) -> int:
1413 return random.randint(0, 1_000)
1415 square = Square(width=1.3)
1417 # `random_number` does not appear in representation
1418 print(repr(square))
1419 #> Square(width=1.3, area=1.69)
1421 print(square.random_number)
1422 #> 3
1424 square.area = 4
1426 print(square.model_dump_json(by_alias=True))
1427 #> {"width":2.0,"area":4.0,"the magic number":3}
1428 ```
1430 !!! warning "Overriding with `computed_field`"
1431 You can't override a field from a parent class with a `computed_field` in the child class.
1432 `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either.
1433 See the example below:
1435 ```python
1436 from pydantic import BaseModel, computed_field
1438 class Parent(BaseModel):
1439 a: str
1441 try:
1443 class Child(Parent):
1444 @computed_field
1445 @property
1446 def a(self) -> str:
1447 return 'new a'
1449 except TypeError as e:
1450 print(e)
1451 '''
1452 Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
1453 '''
1454 ```
1456 Private properties decorated with `@computed_field` have `repr=False` by default.
1458 ```python
1459 from functools import cached_property
1461 from pydantic import BaseModel, computed_field
1463 class Model(BaseModel):
1464 foo: int
1466 @computed_field
1467 @cached_property
1468 def _private_cached_property(self) -> int:
1469 return -self.foo
1471 @computed_field
1472 @property
1473 def _private_property(self) -> int:
1474 return -self.foo
1476 m = Model(foo=1)
1477 print(repr(m))
1478 #> Model(foo=1)
1479 ```
1481 Args:
1482 func: the function to wrap.
1483 alias: alias to use when serializing this computed field, only used when `by_alias=True`
1484 alias_priority: priority of the alias. This affects whether an alias generator is used
1485 title: Title to use when including this computed field in JSON Schema
1486 field_title_generator: A callable that takes a field name and returns title for it.
1487 description: Description to use when including this computed field in JSON Schema, defaults to the function's
1488 docstring
1489 deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport).
1490 to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the
1491 `deprecated` decorator.
1492 examples: Example values to use when including this computed field in JSON Schema
1493 json_schema_extra: A dict or callable to provide extra JSON schema properties.
1494 repr: whether to include this computed field in model repr.
1495 Default is `False` for private properties and `True` for public properties.
1496 return_type: optional return for serialization logic to expect when serializing to JSON, if included
1497 this must be correct, otherwise a `TypeError` is raised.
1498 If you don't include a return type Any is used, which does runtime introspection to handle arbitrary
1499 objects.
1501 Returns:
1502 A proxy wrapper for the property.
1503 """
1505 def dec(f: Any) -> Any: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1506 nonlocal description, deprecated, return_type, alias_priority
1507 unwrapped = _decorators.unwrap_wrapped_function(f) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1509 if description is None and unwrapped.__doc__: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1510 description = inspect.cleandoc(unwrapped.__doc__) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1512 if deprecated is None and hasattr(unwrapped, '__deprecated__'): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1513 deprecated = unwrapped.__deprecated__ 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1515 # if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now
1516 f = _decorators.ensure_property(f) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1517 alias_priority = (alias_priority or 2) if alias is not None else None 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1519 if repr is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1520 repr_: bool = not _wrapped_property_is_private(property_=f) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1521 else:
1522 repr_ = repr 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1524 dec_info = ComputedFieldInfo( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1525 f,
1526 return_type,
1527 alias,
1528 alias_priority,
1529 title,
1530 field_title_generator,
1531 description,
1532 deprecated,
1533 examples,
1534 json_schema_extra,
1535 repr_,
1536 )
1537 return _decorators.PydanticDescriptorProxy(f, dec_info) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1539 if func is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1540 return dec 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi
1541 else:
1542 return dec(func) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi