Coverage for pydantic/fields.py: 91.28%
490 statements
« prev ^ index » next coverage.py v7.10.0, created at 2025-07-26 11:49 +0000
« prev ^ index » next coverage.py v7.10.0, created at 2025-07-26 11:49 +0000
1"""Defining fields on models."""
3from __future__ import annotations as _annotations 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
5import dataclasses 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
6import inspect 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
7import sys 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
8import typing 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
9from collections.abc import Callable, Mapping 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
10from copy import copy 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
11from dataclasses import Field as DataclassField 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
12from functools import cached_property 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
13from typing import Annotated, Any, ClassVar, Literal, TypeVar, cast, final, overload 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
14from warnings import warn 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
16import annotated_types 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
17import typing_extensions 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
18from pydantic_core import MISSING, PydanticUndefined 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
19from typing_extensions import Self, TypeAlias, Unpack, deprecated 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
20from typing_inspection import typing_objects 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
21from typing_inspection.introspection import UNKNOWN, AnnotationSource, ForbiddenQualifier, Qualifier, inspect_annotation 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
23from . import types 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
24from ._internal import _decorators, _fields, _generics, _internal_dataclass, _repr, _typing_extra, _utils 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
25from ._internal._namespace_utils import GlobalsNamespace, MappingNamespace 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
26from .aliases import AliasChoices, AliasGenerator, AliasPath 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
27from .config import JsonDict 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
28from .errors import PydanticForbiddenQualifier, PydanticUserError 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
29from .json_schema import PydanticJsonSchemaWarning 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
30from .warnings import PydanticDeprecatedSince20 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
32if typing.TYPE_CHECKING: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
33 from ._internal._config import ConfigWrapper
34 from ._internal._repr import ReprArgs 1i
35else:
36 # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
37 # and https://youtrack.jetbrains.com/issue/PY-51428
38 DeprecationWarning = PydanticDeprecatedSince20 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
40__all__ = 'Field', 'PrivateAttr', 'computed_field' 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
43_Unset: Any = PydanticUndefined 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
45if sys.version_info >= (3, 13): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
46 import warnings 1abopqcdrstPefuvw
48 Deprecated: TypeAlias = warnings.deprecated | deprecated 1abopqcdrstPefuvw
49else:
50 Deprecated: TypeAlias = deprecated 1JKxyzAghniLMBCDEjkNOFGHIlm
53class _FromFieldInfoInputs(typing_extensions.TypedDict, total=False): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
54 """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.from_field`."""
56 # TODO PEP 747: use TypeForm:
57 annotation: type[Any] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
58 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
59 alias: str | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
60 alias_priority: int | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
61 validation_alias: str | AliasPath | AliasChoices | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
62 serialization_alias: str | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
63 title: str | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
64 field_title_generator: Callable[[str, FieldInfo], str] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
65 description: str | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
66 examples: list[Any] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
67 exclude: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
68 gt: annotated_types.SupportsGt | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
69 ge: annotated_types.SupportsGe | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
70 lt: annotated_types.SupportsLt | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
71 le: annotated_types.SupportsLe | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
72 multiple_of: float | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
73 strict: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
74 min_length: int | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
75 max_length: int | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
76 pattern: str | typing.Pattern[str] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
77 allow_inf_nan: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
78 max_digits: int | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
79 decimal_places: int | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
80 union_mode: Literal['smart', 'left_to_right'] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
81 discriminator: str | types.Discriminator | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
82 deprecated: Deprecated | str | bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
83 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
84 frozen: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
85 validate_default: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
86 repr: bool 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
87 init: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
88 init_var: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
89 kw_only: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
90 coerce_numbers_to_str: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
91 fail_fast: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
94class _FieldInfoInputs(_FromFieldInfoInputs, total=False): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
95 """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.__init__`."""
97 default: Any 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
100@final 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
101class FieldInfo(_repr.Representation): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
102 """This class holds information about a field.
104 `FieldInfo` is used for any field definition regardless of whether the [`Field()`][pydantic.fields.Field]
105 function is explicitly used.
107 !!! warning
108 You generally shouldn't be creating `FieldInfo` directly, you'll only need to use it when accessing
109 [`BaseModel`][pydantic.main.BaseModel] `.model_fields` internals.
111 Attributes:
112 annotation: The type annotation of the field.
113 default: The default value of the field.
114 default_factory: A callable to generate the default value. The callable can either take 0 arguments
115 (in which case it is called as is) or a single argument containing the already validated data.
116 alias: The alias name of the field.
117 alias_priority: The priority of the field's alias.
118 validation_alias: The validation alias of the field.
119 serialization_alias: The serialization alias of the field.
120 title: The title of the field.
121 field_title_generator: A callable that takes a field name and returns title for it.
122 description: The description of the field.
123 examples: List of examples of the field.
124 exclude: Whether to exclude the field from the model serialization.
125 discriminator: Field name or Discriminator for discriminating the type in a tagged union.
126 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
127 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
128 json_schema_extra: A dict or callable to provide extra JSON schema properties.
129 frozen: Whether the field is frozen.
130 validate_default: Whether to validate the default value of the field.
131 repr: Whether to include the field in representation of the model.
132 init: Whether the field should be included in the constructor of the dataclass.
133 init_var: Whether the field should _only_ be included in the constructor of the dataclass, and not stored.
134 kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
135 metadata: List of metadata constraints.
136 """
138 annotation: type[Any] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
139 default: Any 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
140 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
141 alias: str | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
142 alias_priority: int | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
143 validation_alias: str | AliasPath | AliasChoices | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
144 serialization_alias: str | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
145 title: str | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
146 field_title_generator: Callable[[str, FieldInfo], str] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
147 description: str | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
148 examples: list[Any] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
149 exclude: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
150 discriminator: str | types.Discriminator | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
151 deprecated: Deprecated | str | bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
152 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
153 frozen: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
154 validate_default: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
155 repr: bool 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
156 init: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
157 init_var: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
158 kw_only: bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
159 metadata: list[Any] 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
161 __slots__ = ( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
162 'annotation',
163 'default',
164 'default_factory',
165 'alias',
166 'alias_priority',
167 'validation_alias',
168 'serialization_alias',
169 'title',
170 'field_title_generator',
171 'description',
172 'examples',
173 'exclude',
174 'discriminator',
175 'deprecated',
176 'json_schema_extra',
177 'frozen',
178 'validate_default',
179 'repr',
180 'init',
181 'init_var',
182 'kw_only',
183 'metadata',
184 '_attributes_set',
185 '_qualifiers',
186 '_complete',
187 '_original_assignment',
188 '_original_annotation',
189 )
191 # used to convert kwargs to metadata/constraints,
192 # None has a special meaning - these items are collected into a `PydanticGeneralMetadata`
193 metadata_lookup: ClassVar[dict[str, typing.Callable[[Any], Any] | None]] = { 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
194 'strict': types.Strict,
195 'gt': annotated_types.Gt,
196 'ge': annotated_types.Ge,
197 'lt': annotated_types.Lt,
198 'le': annotated_types.Le,
199 'multiple_of': annotated_types.MultipleOf,
200 'min_length': annotated_types.MinLen,
201 'max_length': annotated_types.MaxLen,
202 'pattern': None,
203 'allow_inf_nan': None,
204 'max_digits': None,
205 'decimal_places': None,
206 'union_mode': None,
207 'coerce_numbers_to_str': None,
208 'fail_fast': types.FailFast,
209 }
211 def __init__(self, **kwargs: Unpack[_FieldInfoInputs]) -> None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
212 """This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
213 or one of the constructor classmethods.
215 See the signature of `pydantic.fields.Field` for more details about the expected arguments.
216 """
217 self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset and k not in self.metadata_lookup} 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
218 kwargs = {k: _DefaultValues.get(k) if v is _Unset else v for k, v in kwargs.items()} # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
219 self.annotation = kwargs.get('annotation') 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
221 default = kwargs.pop('default', PydanticUndefined) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
222 if default is Ellipsis: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
223 self.default = PydanticUndefined 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
224 self._attributes_set.pop('default', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
225 else:
226 self.default = default 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
228 self.default_factory = kwargs.pop('default_factory', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
230 if self.default is not PydanticUndefined and self.default_factory is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
231 raise TypeError('cannot specify both default and default_factory') 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
233 self.alias = kwargs.pop('alias', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
234 self.validation_alias = kwargs.pop('validation_alias', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
235 self.serialization_alias = kwargs.pop('serialization_alias', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
236 alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias)) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
237 self.alias_priority = kwargs.pop('alias_priority', None) or 2 if alias_is_set else None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
238 self.title = kwargs.pop('title', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
239 self.field_title_generator = kwargs.pop('field_title_generator', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
240 self.description = kwargs.pop('description', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
241 self.examples = kwargs.pop('examples', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
242 self.exclude = kwargs.pop('exclude', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
243 self.discriminator = kwargs.pop('discriminator', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
244 # For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden
245 self.deprecated = kwargs.pop('deprecated', getattr(self, 'deprecated', None)) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
246 self.repr = kwargs.pop('repr', True) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
247 self.json_schema_extra = kwargs.pop('json_schema_extra', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
248 self.validate_default = kwargs.pop('validate_default', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
249 self.frozen = kwargs.pop('frozen', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
250 # currently only used on dataclasses
251 self.init = kwargs.pop('init', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
252 self.init_var = kwargs.pop('init_var', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
253 self.kw_only = kwargs.pop('kw_only', None) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
255 self.metadata = self._collect_metadata(kwargs) # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
257 # Private attributes:
258 self._qualifiers: set[Qualifier] = set() 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
259 # Used to rebuild FieldInfo instances:
260 self._complete = True 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
261 self._original_annotation: Any = PydanticUndefined 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
262 self._original_assignment: Any = PydanticUndefined 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
264 @staticmethod 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
265 def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
266 """Create a new `FieldInfo` object with the `Field` function.
268 Args:
269 default: The default value for the field. Defaults to Undefined.
270 **kwargs: Additional arguments dictionary.
272 Raises:
273 TypeError: If 'annotation' is passed as a keyword argument.
275 Returns:
276 A new FieldInfo object with the given parameters.
278 Example:
279 This is how you can create a field with default value like this:
281 ```python
282 import pydantic
284 class MyModel(pydantic.BaseModel):
285 foo: int = pydantic.Field(4)
286 ```
287 """
288 if 'annotation' in kwargs: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
289 raise TypeError('"annotation" is not permitted as a Field keyword argument') 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
290 return FieldInfo(default=default, **kwargs) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
292 @staticmethod 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
293 def from_annotation(annotation: type[Any], *, _source: AnnotationSource = AnnotationSource.ANY) -> FieldInfo: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
294 """Creates a `FieldInfo` instance from a bare annotation.
296 This function is used internally to create a `FieldInfo` from a bare annotation like this:
298 ```python
299 import pydantic
301 class MyModel(pydantic.BaseModel):
302 foo: int # <-- like this
303 ```
305 We also account for the case where the annotation can be an instance of `Annotated` and where
306 one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
308 ```python
309 from typing import Annotated
311 import annotated_types
313 import pydantic
315 class MyModel(pydantic.BaseModel):
316 foo: Annotated[int, annotated_types.Gt(42)]
317 bar: Annotated[int, pydantic.Field(gt=42)]
318 ```
320 Args:
321 annotation: An annotation object.
323 Returns:
324 An instance of the field metadata.
325 """
326 try: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
327 inspected_ann = inspect_annotation( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
328 annotation,
329 annotation_source=_source,
330 unpack_type_aliases='skip',
331 )
332 except ForbiddenQualifier as e: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
333 raise PydanticForbiddenQualifier(e.qualifier, annotation) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
335 # TODO check for classvar and error?
337 # No assigned value, this happens when using a bare `Final` qualifier (also for other
338 # qualifiers, but they shouldn't appear here). In this case we infer the type as `Any`
339 # because we don't have any assigned value.
340 type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
341 final = 'final' in inspected_ann.qualifiers 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
342 metadata = inspected_ann.metadata 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
344 attr_overrides = {'annotation': type_expr} 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
345 if final: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
346 attr_overrides['frozen'] = True 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
347 field_info = FieldInfo._construct(metadata, **attr_overrides) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
348 field_info._qualifiers = inspected_ann.qualifiers 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
349 return field_info 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
351 @staticmethod 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
352 def from_annotated_attribute( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
353 annotation: type[Any], default: Any, *, _source: AnnotationSource = AnnotationSource.ANY
354 ) -> FieldInfo:
355 """Create `FieldInfo` from an annotation with a default value.
357 This is used in cases like the following:
359 ```python
360 from typing import Annotated
362 import annotated_types
364 import pydantic
366 class MyModel(pydantic.BaseModel):
367 foo: int = 4 # <-- like this
368 bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
369 spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
370 ```
372 Args:
373 annotation: The type annotation of the field.
374 default: The default value of the field.
376 Returns:
377 A field object with the passed values.
378 """
379 if annotation is not MISSING and annotation is default: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
380 raise PydanticUserError( 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
381 'Error when building FieldInfo from annotated attribute. '
382 "Make sure you don't have any field name clashing with a type annotation.",
383 code='unevaluable-type-annotation',
384 )
386 try: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
387 inspected_ann = inspect_annotation( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
388 annotation,
389 annotation_source=_source,
390 unpack_type_aliases='skip',
391 )
392 except ForbiddenQualifier as e: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
393 raise PydanticForbiddenQualifier(e.qualifier, annotation) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
395 # TODO check for classvar and error?
397 # TODO infer from the default, this can be done in v3 once we treat final fields with
398 # a default as proper fields and not class variables:
399 type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
400 final = 'final' in inspected_ann.qualifiers 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
401 metadata = inspected_ann.metadata 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
403 # HACK 1: the order in which the metadata is merged is inconsistent; we need to prepend
404 # metadata from the assignment at the beginning of the metadata. Changing this is only
405 # possible in v3 (at least). See https://github.com/pydantic/pydantic/issues/10507
406 prepend_metadata: list[Any] | None = None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
407 attr_overrides = {'annotation': type_expr} 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
408 if final: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
409 attr_overrides['frozen'] = True 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
411 # HACK 2: FastAPI is subclassing `FieldInfo` and historically expected the actual
412 # instance's type to be preserved when constructing new models with its subclasses as assignments.
413 # This code is never reached by Pydantic itself, and in an ideal world this shouldn't be necessary.
414 if not metadata and isinstance(default, FieldInfo) and type(default) is not FieldInfo: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
415 field_info = default._copy() 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
416 field_info._attributes_set.update(attr_overrides) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
417 for k, v in attr_overrides.items(): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
418 setattr(field_info, k, v) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
419 return field_info 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
421 if isinstance(default, FieldInfo): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
422 default_copy = default._copy() # Copy unnecessary when we remove HACK 1. 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
423 prepend_metadata = default_copy.metadata 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
424 default_copy.metadata = [] 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
425 metadata = metadata + [default_copy] 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
426 elif isinstance(default, dataclasses.Field): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
427 from_field = FieldInfo._from_dataclass_field(default) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
428 prepend_metadata = from_field.metadata # Unnecessary when we remove HACK 1. 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
429 from_field.metadata = [] 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
430 metadata = metadata + [from_field] 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
431 if 'init_var' in inspected_ann.qualifiers: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
432 attr_overrides['init_var'] = True 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
433 if (init := getattr(default, 'init', None)) is not None: 433 ↛ 435line 433 didn't jump to line 435 because the condition on line 433 was always true1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
434 attr_overrides['init'] = init 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
435 if (kw_only := getattr(default, 'kw_only', None)) is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
436 attr_overrides['kw_only'] = kw_only 1xyzAghabopqiBCDEjkcdrstPFGHIlmefuvw
437 else:
438 # `default` is the actual default value
439 attr_overrides['default'] = default 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
441 field_info = FieldInfo._construct( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
442 prepend_metadata + metadata if prepend_metadata is not None else metadata, **attr_overrides
443 )
444 field_info._qualifiers = inspected_ann.qualifiers 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
445 return field_info 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
447 @classmethod 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
448 def _construct(cls, metadata: list[Any], **attr_overrides: Any) -> Self: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
449 """Construct the final `FieldInfo` instance, by merging the possibly existing `FieldInfo` instances from the metadata.
451 With the following example:
453 ```python {test="skip" lint="skip"}
454 class Model(BaseModel):
455 f: Annotated[int, Gt(1), Field(description='desc', lt=2)]
456 ```
458 `metadata` refers to the metadata elements of the `Annotated` form. This metadata is iterated over from left to right:
460 - If the element is a `Field()` function (which is itself a `FieldInfo` instance), the field attributes (such as
461 `description`) are saved to be set on the final `FieldInfo` instance.
462 On the other hand, some kwargs (such as `lt`) are stored as `metadata` (see `FieldInfo.__init__()`, calling
463 `FieldInfo._collect_metadata()`). In this case, the final metadata list is extended with the one from this instance.
464 - Else, the element is considered as a single metadata object, and is appended to the final metadata list.
466 Args:
467 metadata: The list of metadata elements to merge together. If the `FieldInfo` instance to be constructed is for
468 a field with an assigned `Field()`, this `Field()` assignment should be added as the last element of the
469 provided metadata.
470 **attr_overrides: Extra attributes that should be set on the final merged `FieldInfo` instance.
472 Returns:
473 The final merged `FieldInfo` instance.
474 """
475 merged_metadata: list[Any] = [] 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
476 merged_kwargs: dict[str, Any] = {} 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
478 for meta in metadata: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
479 if isinstance(meta, FieldInfo): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
480 merged_metadata.extend(meta.metadata) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
482 new_js_extra: JsonDict | None = None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
483 current_js_extra = meta.json_schema_extra 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
484 if current_js_extra is not None and 'json_schema_extra' in merged_kwargs: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
485 # We need to merge `json_schema_extra`'s:
486 existing_js_extra = merged_kwargs['json_schema_extra'] 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
487 if isinstance(existing_js_extra, dict): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
488 if isinstance(current_js_extra, dict): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
489 new_js_extra = { 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
490 **existing_js_extra,
491 **current_js_extra,
492 }
493 elif callable(current_js_extra): 493 ↛ 508line 493 didn't jump to line 508 because the condition on line 493 was always true1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
494 warn( 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
495 'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
496 'The `callable` type is being ignored. '
497 "If you'd like support for this behavior, please open an issue on pydantic.",
498 UserWarning,
499 )
500 elif callable(existing_js_extra) and isinstance(current_js_extra, dict): 500 ↛ 508line 500 didn't jump to line 508 because the condition on line 500 was always true1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
501 warn( 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
502 'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
503 'The `callable` type is being ignored. '
504 "If you'd like support for this behavior, please open an issue on pydantic.",
505 UserWarning,
506 )
508 merged_kwargs.update(meta._attributes_set) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
509 if new_js_extra is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
510 merged_kwargs['json_schema_extra'] = new_js_extra 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
511 elif typing_objects.is_deprecated(meta): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
512 merged_kwargs['deprecated'] = meta 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
513 else:
514 merged_metadata.append(meta) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
516 merged_kwargs.update(attr_overrides) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
517 merged_field_info = cls(**merged_kwargs) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
518 merged_field_info.metadata = merged_metadata 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
519 return merged_field_info 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
521 @staticmethod 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
522 @typing_extensions.deprecated( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
523 "The 'merge_field_infos()' method is deprecated and will be removed in a future version. "
524 'If you relied on this method, please open an issue in the Pydantic issue tracker.',
525 category=None,
526 )
527 def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
528 """Merge `FieldInfo` instances keeping only explicitly set attributes.
530 Later `FieldInfo` instances override earlier ones.
532 Returns:
533 FieldInfo: A merged FieldInfo instance.
534 """
535 if len(field_infos) == 1: 535 ↛ 550line 535 didn't jump to line 550 because the condition on line 535 was always true1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
536 # No merging necessary, but we still need to make a copy and apply the overrides
537 field_info = field_infos[0]._copy() 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
538 field_info._attributes_set.update(overrides) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
540 default_override = overrides.pop('default', PydanticUndefined) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
541 if default_override is Ellipsis: 541 ↛ 542line 541 didn't jump to line 542 because the condition on line 541 was never true1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
542 default_override = PydanticUndefined
543 if default_override is not PydanticUndefined: 543 ↛ 546line 543 didn't jump to line 546 because the condition on line 543 was always true1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
544 field_info.default = default_override 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
546 for k, v in overrides.items(): 546 ↛ 547line 546 didn't jump to line 547 because the loop on line 546 never started1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
547 setattr(field_info, k, v)
548 return field_info # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
550 merged_field_info_kwargs: dict[str, Any] = {}
551 metadata = {}
552 for field_info in field_infos:
553 attributes_set = field_info._attributes_set.copy()
555 try:
556 json_schema_extra = attributes_set.pop('json_schema_extra')
557 existing_json_schema_extra = merged_field_info_kwargs.get('json_schema_extra')
559 if existing_json_schema_extra is None:
560 merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
561 if isinstance(existing_json_schema_extra, dict):
562 if isinstance(json_schema_extra, dict):
563 merged_field_info_kwargs['json_schema_extra'] = {
564 **existing_json_schema_extra,
565 **json_schema_extra,
566 }
567 if callable(json_schema_extra):
568 warn(
569 'Composing `dict` and `callable` type `json_schema_extra` is not supported.'
570 'The `callable` type is being ignored.'
571 "If you'd like support for this behavior, please open an issue on pydantic.",
572 PydanticJsonSchemaWarning,
573 )
574 elif callable(json_schema_extra):
575 # if ever there's a case of a callable, we'll just keep the last json schema extra spec
576 merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
577 except KeyError:
578 pass
580 # later FieldInfo instances override everything except json_schema_extra from earlier FieldInfo instances
581 merged_field_info_kwargs.update(attributes_set)
583 for x in field_info.metadata:
584 if not isinstance(x, FieldInfo):
585 metadata[type(x)] = x
587 merged_field_info_kwargs.update(overrides)
588 field_info = FieldInfo(**merged_field_info_kwargs)
589 field_info.metadata = list(metadata.values())
590 return field_info
592 @staticmethod 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
593 def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
594 """Return a new `FieldInfo` instance from a `dataclasses.Field` instance.
596 Args:
597 dc_field: The `dataclasses.Field` instance to convert.
599 Returns:
600 The corresponding `FieldInfo` instance.
602 Raises:
603 TypeError: If any of the `FieldInfo` kwargs does not match the `dataclass.Field` kwargs.
604 """
605 default = dc_field.default 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
606 if default is dataclasses.MISSING: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
607 default = _Unset 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
609 if dc_field.default_factory is dataclasses.MISSING: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
610 default_factory = _Unset 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
611 else:
612 default_factory = dc_field.default_factory 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
614 # use the `Field` function so in correct kwargs raise the correct `TypeError`
615 dc_field_metadata = {k: v for k, v in dc_field.metadata.items() if k in _FIELD_ARG_NAMES} 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
616 if sys.version_info >= (3, 14) and dc_field.doc is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
617 dc_field_metadata['description'] = dc_field.doc 1opqrstuvw
618 return Field(default=default, default_factory=default_factory, repr=dc_field.repr, **dc_field_metadata) # pyright: ignore[reportCallIssue] 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
620 @staticmethod 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
621 def _collect_metadata(kwargs: dict[str, Any]) -> list[Any]: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
622 """Collect annotations from kwargs.
624 Args:
625 kwargs: Keyword arguments passed to the function.
627 Returns:
628 A list of metadata objects - a combination of `annotated_types.BaseMetadata` and
629 `PydanticMetadata`.
630 """
631 metadata: list[Any] = [] 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
632 general_metadata = {} 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
633 for key, value in list(kwargs.items()): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
634 try: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
635 marker = FieldInfo.metadata_lookup[key] 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
636 except KeyError: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
637 continue 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
639 del kwargs[key] 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
640 if value is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
641 if marker is None: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
642 general_metadata[key] = value 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
643 else:
644 metadata.append(marker(value)) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
645 if general_metadata: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
646 metadata.append(_fields.pydantic_general_metadata(**general_metadata)) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
647 return metadata 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
649 @property 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
650 def deprecation_message(self) -> str | None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
651 """The deprecation message to be emitted, or `None` if not set."""
652 if self.deprecated is None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
653 return None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
654 if isinstance(self.deprecated, bool): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
655 return 'deprecated' if self.deprecated else None 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
656 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
658 @property 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
659 def default_factory_takes_validated_data(self) -> bool | None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
660 """Whether the provided default factory callable has a validated data parameter.
662 Returns `None` if no default factory is set.
663 """
664 if self.default_factory is not None: 664 ↛ exitline 664 didn't return from function 'default_factory_takes_validated_data' because the condition on line 664 was always true1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
665 return _fields.takes_validated_data_argument(self.default_factory) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
667 @overload 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
668 def get_default( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
669 self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
670 ) -> Any: ... 1ghabnijkcdPlmef
672 @overload 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
673 def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ... 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
675 def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
676 """Get the default value.
678 We expose an option for whether to call the default_factory (if present), as calling it may
679 result in side effects that we want to avoid. However, there are times when it really should
680 be called (namely, when instantiating a model via `model_construct`).
682 Args:
683 call_default_factory: Whether to call the default factory or not.
684 validated_data: The already validated data to be passed to the default factory.
686 Returns:
687 The default value, calling the default factory if requested or `None` if not set.
688 """
689 if self.default_factory is None: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
690 return _utils.smart_deepcopy(self.default) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
691 elif call_default_factory: 691 ↛ 703line 691 didn't jump to line 703 because the condition on line 691 was always true1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
692 if self.default_factory_takes_validated_data: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
693 fac = cast('Callable[[dict[str, Any]], Any]', self.default_factory) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
694 if validated_data is None: 694 ↛ 695line 694 didn't jump to line 695 because the condition on line 694 was never true1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
695 raise ValueError(
696 "The default factory requires the 'validated_data' argument, which was not provided when calling 'get_default'."
697 )
698 return fac(validated_data) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
699 else:
700 fac = cast('Callable[[], Any]', self.default_factory) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
701 return fac() 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
702 else:
703 return None
705 def is_required(self) -> bool: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
706 """Check if the field is required (i.e., does not have a default value or factory).
708 Returns:
709 `True` if the field is required, `False` otherwise.
710 """
711 return self.default is PydanticUndefined and self.default_factory is None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
713 def rebuild_annotation(self) -> Any: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
714 """Attempts to rebuild the original annotation for use in function signatures.
716 If metadata is present, it adds it to the original annotation using
717 `Annotated`. Otherwise, it returns the original annotation as-is.
719 Note that because the metadata has been flattened, the original annotation
720 may not be reconstructed exactly as originally provided, e.g. if the original
721 type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
723 Returns:
724 The rebuilt annotation.
725 """
726 if not self.metadata: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
727 return self.annotation 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
728 else:
729 # Annotated arguments must be a tuple
730 return Annotated[(self.annotation, *self.metadata)] # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
732 def apply_typevars_map( 1JKxyzAghabopqLMBCDEjkcdrstPNOFGHIlmefuvw
733 self,
734 typevars_map: Mapping[TypeVar, Any] | None,
735 globalns: GlobalsNamespace | None = None,
736 localns: MappingNamespace | None = None,
737 ) -> None:
738 """Apply a `typevars_map` to the annotation.
740 This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
742 This method applies the `typevars_map` to the annotation in place.
744 Args:
745 typevars_map: A dictionary mapping type variables to their concrete types.
746 globalns: The globals namespace to use during type annotation evaluation.
747 localns: The locals namespace to use during type annotation evaluation.
749 See Also:
750 pydantic._internal._generics.replace_types is used for replacing the typevars with
751 their concrete types.
752 """
753 annotation = _generics.replace_types(self.annotation, typevars_map) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
754 annotation, evaluated = _typing_extra.try_eval_type(annotation, globalns, localns) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
755 self.annotation = annotation 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
756 if not evaluated: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
757 self._complete = False 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
758 self._original_annotation = self.annotation 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
760 def _copy(self) -> Self: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
761 """Return a copy of the `FieldInfo` instance."""
762 # Note: we can't define a custom `__copy__()`, as `FieldInfo` is being subclassed
763 # by some third-party libraries with extra attributes defined (and as `FieldInfo`
764 # is slotted, we can't make a copy of the `__dict__`).
765 copied = copy(self) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
766 for attr_name in ('metadata', '_attributes_set', '_qualifiers'): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
767 # Apply "deep-copy" behavior on collections attributes:
768 value = getattr(copied, attr_name).copy() 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
769 setattr(copied, attr_name, value) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
771 return copied 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
773 def __repr_args__(self) -> ReprArgs: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
774 yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation)) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
775 yield 'required', self.is_required() 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
777 for s in self.__slots__: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
778 # TODO: properly make use of the protocol (https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol)
779 # By yielding a three-tuple:
780 if s in ( 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
781 'annotation',
782 '_attributes_set',
783 '_qualifiers',
784 '_complete',
785 '_original_assignment',
786 '_original_annotation',
787 ):
788 continue 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
789 elif s == 'metadata' and not self.metadata: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
790 continue 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
791 elif s == 'repr' and self.repr is True: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
792 continue 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
793 if s == 'frozen' and self.frozen is False: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
794 continue 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
795 if s == 'validation_alias' and self.validation_alias == self.alias: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
796 continue 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
797 if s == 'serialization_alias' and self.serialization_alias == self.alias: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
798 continue 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
799 if s == 'default' and self.default is not PydanticUndefined: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
800 yield 'default', self.default 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
801 elif s == 'default_factory' and self.default_factory is not None: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
802 yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory)) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
803 else:
804 value = getattr(self, s) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
805 if value is not None and value is not PydanticUndefined: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
806 yield s, value 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
809class _EmptyKwargs(typing_extensions.TypedDict): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
810 """This class exists solely to ensure that type checking warns about passing `**extra` in `Field`."""
813_DefaultValues = { 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
814 'default': ...,
815 'default_factory': None,
816 'alias': None,
817 'alias_priority': None,
818 'validation_alias': None,
819 'serialization_alias': None,
820 'title': None,
821 'description': None,
822 'examples': None,
823 'exclude': None,
824 'discriminator': None,
825 'json_schema_extra': None,
826 'frozen': None,
827 'validate_default': None,
828 'repr': True,
829 'init': None,
830 'init_var': None,
831 'kw_only': None,
832 'pattern': None,
833 'strict': None,
834 'gt': None,
835 'ge': None,
836 'lt': None,
837 'le': None,
838 'multiple_of': None,
839 'allow_inf_nan': None,
840 'max_digits': None,
841 'decimal_places': None,
842 'min_length': None,
843 'max_length': None,
844 'coerce_numbers_to_str': None,
845}
848_T = TypeVar('_T') 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
851# NOTE: Actual return type is 'FieldInfo', but we want to help type checkers
852# to understand the magic that happens at runtime with the following overloads:
853@overload # type hint the return value as `Any` to avoid type checking regressions when using `...`. 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
854def Field( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
855 default: ellipsis, # noqa: F821 # TODO: use `_typing_extra.EllipsisType` when we drop Py3.9 1ghabnijkcdPlmef
856 *,
857 alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
858 alias_priority: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
859 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
860 serialization_alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
861 title: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
862 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
863 description: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
864 examples: list[Any] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
865 exclude: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
866 discriminator: str | types.Discriminator | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
867 deprecated: Deprecated | str | bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
868 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
869 frozen: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
870 validate_default: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
871 repr: bool = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
872 init: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
873 init_var: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
874 kw_only: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
875 pattern: str | typing.Pattern[str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
876 strict: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
877 coerce_numbers_to_str: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
878 gt: annotated_types.SupportsGt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
879 ge: annotated_types.SupportsGe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
880 lt: annotated_types.SupportsLt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
881 le: annotated_types.SupportsLe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
882 multiple_of: float | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
883 allow_inf_nan: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
884 max_digits: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
885 decimal_places: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
886 min_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
887 max_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
888 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
889 fail_fast: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
890 **extra: Unpack[_EmptyKwargs], 1ghabnijkcdPlmef
891) -> Any: ... 1ghabnijkcdPlmef
892@overload # `default` argument set, validate_default=True (no type checking on the default value) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
893def Field( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
894 default: Any, 1ghabnijkcdPlmef
895 *,
896 alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
897 alias_priority: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
898 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
899 serialization_alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
900 title: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
901 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
902 description: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
903 examples: list[Any] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
904 exclude: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
905 discriminator: str | types.Discriminator | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
906 deprecated: Deprecated | str | bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
907 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
908 frozen: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
909 validate_default: Literal[True], 1ghabnijkcdPlmef
910 repr: bool = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
911 init: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
912 init_var: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
913 kw_only: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
914 pattern: str | typing.Pattern[str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
915 strict: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
916 coerce_numbers_to_str: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
917 gt: annotated_types.SupportsGt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
918 ge: annotated_types.SupportsGe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
919 lt: annotated_types.SupportsLt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
920 le: annotated_types.SupportsLe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
921 multiple_of: float | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
922 allow_inf_nan: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
923 max_digits: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
924 decimal_places: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
925 min_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
926 max_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
927 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
928 fail_fast: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
929 **extra: Unpack[_EmptyKwargs], 1ghabnijkcdPlmef
930) -> Any: ... 1ghabnijkcdPlmef
931@overload # `default` argument set, validate_default=False or unset 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
932def Field( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
933 default: _T, 1ghabnijkcdPlmef
934 *,
935 alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
936 alias_priority: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
937 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
938 serialization_alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
939 title: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
940 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
941 description: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
942 examples: list[Any] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
943 exclude: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
944 discriminator: str | types.Discriminator | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
945 deprecated: Deprecated | str | bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
946 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
947 frozen: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
948 validate_default: Literal[False] = ..., 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
949 repr: bool = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
950 init: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
951 init_var: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
952 kw_only: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
953 pattern: str | typing.Pattern[str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
954 strict: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
955 coerce_numbers_to_str: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
956 gt: annotated_types.SupportsGt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
957 ge: annotated_types.SupportsGe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
958 lt: annotated_types.SupportsLt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
959 le: annotated_types.SupportsLe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
960 multiple_of: float | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
961 allow_inf_nan: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
962 max_digits: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
963 decimal_places: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
964 min_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
965 max_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
966 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
967 fail_fast: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
968 **extra: Unpack[_EmptyKwargs], 1ghabnijkcdPlmef
969) -> _T: ... 1ghabnijkcdPlmef
970@overload # `default_factory` argument set, validate_default=True (no type checking on the default value) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
971def Field( # pyright: ignore[reportOverlappingOverload] 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
972 *,
973 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any], 1ghabnijkcdPlmef
974 alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
975 alias_priority: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
976 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
977 serialization_alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
978 title: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
979 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
980 description: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
981 examples: list[Any] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
982 exclude: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
983 discriminator: str | types.Discriminator | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
984 deprecated: Deprecated | str | bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
985 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
986 frozen: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
987 validate_default: Literal[True], 1ghabnijkcdPlmef
988 repr: bool = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
989 init: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
990 init_var: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
991 kw_only: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
992 pattern: str | typing.Pattern[str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
993 strict: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
994 coerce_numbers_to_str: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
995 gt: annotated_types.SupportsGt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
996 ge: annotated_types.SupportsGe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
997 lt: annotated_types.SupportsLt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
998 le: annotated_types.SupportsLe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
999 multiple_of: float | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1000 allow_inf_nan: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1001 max_digits: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1002 decimal_places: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1003 min_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1004 max_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1005 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1006 fail_fast: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1007 **extra: Unpack[_EmptyKwargs], 1ghabnijkcdPlmef
1008) -> Any: ... 1ghabnijkcdPlmef
1009@overload # `default_factory` argument set, validate_default=False or unset 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1010def Field( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1011 *,
1012 default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T], 1ghabnijkcdPlmef
1013 alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1014 alias_priority: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1015 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1016 serialization_alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1017 title: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1018 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1019 description: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1020 examples: list[Any] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1021 exclude: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1022 discriminator: str | types.Discriminator | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1023 deprecated: Deprecated | str | bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1024 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1025 frozen: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1026 validate_default: Literal[False] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1027 repr: bool = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1028 init: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1029 init_var: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1030 kw_only: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1031 pattern: str | typing.Pattern[str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1032 strict: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1033 coerce_numbers_to_str: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1034 gt: annotated_types.SupportsGt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1035 ge: annotated_types.SupportsGe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1036 lt: annotated_types.SupportsLt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1037 le: annotated_types.SupportsLe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1038 multiple_of: float | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1039 allow_inf_nan: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1040 max_digits: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1041 decimal_places: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1042 min_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1043 max_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1044 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1045 fail_fast: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1046 **extra: Unpack[_EmptyKwargs], 1ghabnijkcdPlmef
1047) -> _T: ... 1ghabnijkcdPlmef
1048@overload 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1049def Field( # No default set 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1050 *,
1051 alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1052 alias_priority: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1053 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1054 serialization_alias: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1055 title: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1056 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1057 description: str | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1058 examples: list[Any] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1059 exclude: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1060 discriminator: str | types.Discriminator | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1061 deprecated: Deprecated | str | bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1062 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1063 frozen: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1064 validate_default: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1065 repr: bool = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1066 init: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1067 init_var: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1068 kw_only: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1069 pattern: str | typing.Pattern[str] | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1070 strict: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1071 coerce_numbers_to_str: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1072 gt: annotated_types.SupportsGt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1073 ge: annotated_types.SupportsGe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1074 lt: annotated_types.SupportsLt | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1075 le: annotated_types.SupportsLe | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1076 multiple_of: float | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1077 allow_inf_nan: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1078 max_digits: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1079 decimal_places: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1080 min_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1081 max_length: int | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1082 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1083 fail_fast: bool | None = _Unset, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1084 **extra: Unpack[_EmptyKwargs], 1ghabnijkcdPlmef
1085) -> Any: ... 1ghabnijkcdPlmef
1086def Field( # noqa: C901 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1087 default: Any = PydanticUndefined,
1088 *,
1089 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = _Unset,
1090 alias: str | None = _Unset,
1091 alias_priority: int | None = _Unset,
1092 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
1093 serialization_alias: str | None = _Unset,
1094 title: str | None = _Unset,
1095 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
1096 description: str | None = _Unset,
1097 examples: list[Any] | None = _Unset,
1098 exclude: bool | None = _Unset,
1099 discriminator: str | types.Discriminator | None = _Unset,
1100 deprecated: Deprecated | str | bool | None = _Unset,
1101 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
1102 frozen: bool | None = _Unset,
1103 validate_default: bool | None = _Unset,
1104 repr: bool = _Unset,
1105 init: bool | None = _Unset,
1106 init_var: bool | None = _Unset,
1107 kw_only: bool | None = _Unset,
1108 pattern: str | typing.Pattern[str] | None = _Unset,
1109 strict: bool | None = _Unset,
1110 coerce_numbers_to_str: bool | None = _Unset,
1111 gt: annotated_types.SupportsGt | None = _Unset,
1112 ge: annotated_types.SupportsGe | None = _Unset,
1113 lt: annotated_types.SupportsLt | None = _Unset,
1114 le: annotated_types.SupportsLe | None = _Unset,
1115 multiple_of: float | None = _Unset,
1116 allow_inf_nan: bool | None = _Unset,
1117 max_digits: int | None = _Unset,
1118 decimal_places: int | None = _Unset,
1119 min_length: int | None = _Unset,
1120 max_length: int | None = _Unset,
1121 union_mode: Literal['smart', 'left_to_right'] = _Unset,
1122 fail_fast: bool | None = _Unset,
1123 **extra: Unpack[_EmptyKwargs],
1124) -> Any:
1125 """!!! abstract "Usage Documentation"
1126 [Fields](../concepts/fields.md)
1128 Create a field for objects that can be configured.
1130 Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
1131 apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`.
1133 Note:
1134 - 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`
1136 Args:
1137 default: Default value if the field is not set.
1138 default_factory: A callable to generate the default value. The callable can either take 0 arguments
1139 (in which case it is called as is) or a single argument containing the already validated data.
1140 alias: The name to use for the attribute when validating or serializing by alias.
1141 This is often used for things like converting between snake and camel case.
1142 alias_priority: Priority of the alias. This affects whether an alias generator is used.
1143 validation_alias: Like `alias`, but only affects validation, not serialization.
1144 serialization_alias: Like `alias`, but only affects serialization, not validation.
1145 title: Human-readable title.
1146 field_title_generator: A callable that takes a field name and returns title for it.
1147 description: Human-readable description.
1148 examples: Example values for this field.
1149 exclude: Whether to exclude the field from the model serialization.
1150 discriminator: Field name or Discriminator for discriminating the type in a tagged union.
1151 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
1152 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
1153 json_schema_extra: A dict or callable to provide extra JSON schema properties.
1154 frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.
1155 validate_default: If `True`, apply validation to the default value every time you create an instance.
1156 Otherwise, for performance reasons, the default value of the field is trusted and not validated.
1157 repr: A boolean indicating whether to include the field in the `__repr__` output.
1158 init: Whether the field should be included in the constructor of the dataclass.
1159 (Only applies to dataclasses.)
1160 init_var: Whether the field should _only_ be included in the constructor of the dataclass.
1161 (Only applies to dataclasses.)
1162 kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
1163 (Only applies to dataclasses.)
1164 coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
1165 strict: If `True`, strict validation is applied to the field.
1166 See [Strict Mode](../concepts/strict_mode.md) for details.
1167 gt: Greater than. If set, value must be greater than this. Only applicable to numbers.
1168 ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.
1169 lt: Less than. If set, value must be less than this. Only applicable to numbers.
1170 le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.
1171 multiple_of: Value must be a multiple of this. Only applicable to numbers.
1172 min_length: Minimum length for iterables.
1173 max_length: Maximum length for iterables.
1174 pattern: Pattern for strings (a regular expression).
1175 allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to float and [`Decimal`][decimal.Decimal] numbers.
1176 max_digits: Maximum number of allow digits for strings.
1177 decimal_places: Maximum number of decimal places allowed for numbers.
1178 union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`.
1179 See [Union Mode](../concepts/unions.md#union-modes) for details.
1180 fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected.
1181 This option can be applied only to iterable types (list, tuple, set, and frozenset).
1182 extra: (Deprecated) Extra fields that will be included in the JSON schema.
1184 !!! warning Deprecated
1185 The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
1187 Returns:
1188 A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on
1189 type-annotated fields without causing a type error.
1190 """
1191 # Check deprecated and removed params from V1. This logic should eventually be removed.
1192 const = extra.pop('const', None) # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1193 if const is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1194 raise PydanticUserError('`const` is removed, use `Literal` instead', code='removed-kwargs') 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1196 min_items = extra.pop('min_items', None) # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1197 if min_items is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1198 warn('`min_items` is deprecated and will be removed, use `min_length` instead', DeprecationWarning) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1199 if min_length in (None, _Unset): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1200 min_length = min_items # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1202 max_items = extra.pop('max_items', None) # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1203 if max_items is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1204 warn('`max_items` is deprecated and will be removed, use `max_length` instead', DeprecationWarning) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1205 if max_length in (None, _Unset): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1206 max_length = max_items # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1208 unique_items = extra.pop('unique_items', None) # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1209 if unique_items is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1210 raise PydanticUserError( 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1211 (
1212 '`unique_items` is removed, use `Set` instead'
1213 '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)'
1214 ),
1215 code='removed-kwargs',
1216 )
1218 allow_mutation = extra.pop('allow_mutation', None) # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1219 if allow_mutation is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1220 warn('`allow_mutation` is deprecated and will be removed. use `frozen` instead', DeprecationWarning) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1221 if allow_mutation is False: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1222 frozen = True 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1224 regex = extra.pop('regex', None) # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1225 if regex is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1226 raise PydanticUserError('`regex` is removed. use `pattern` instead', code='removed-kwargs') 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1228 if extra: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1229 warn( 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1230 'Using extra keyword arguments on `Field` is deprecated and will be removed.'
1231 ' Use `json_schema_extra` instead.'
1232 f' (Extra keys: {", ".join(k.__repr__() for k in extra.keys())})',
1233 DeprecationWarning,
1234 )
1235 if not json_schema_extra or json_schema_extra is _Unset: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1236 json_schema_extra = extra # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1238 if ( 1JKxyzAniLMBCDENOFGHI
1239 validation_alias
1240 and validation_alias is not _Unset
1241 and not isinstance(validation_alias, (str, AliasChoices, AliasPath))
1242 ):
1243 raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`') 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1245 if serialization_alias in (_Unset, None) and isinstance(alias, str): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1246 serialization_alias = alias 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1248 if validation_alias in (_Unset, None): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1249 validation_alias = alias 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1251 include = extra.pop('include', None) # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1252 if include is not None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1253 warn('`include` is deprecated and does nothing. It will be removed, use `exclude` instead', DeprecationWarning) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1255 return FieldInfo.from_field( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1256 default,
1257 default_factory=default_factory,
1258 alias=alias,
1259 alias_priority=alias_priority,
1260 validation_alias=validation_alias,
1261 serialization_alias=serialization_alias,
1262 title=title,
1263 field_title_generator=field_title_generator,
1264 description=description,
1265 examples=examples,
1266 exclude=exclude,
1267 discriminator=discriminator,
1268 deprecated=deprecated,
1269 json_schema_extra=json_schema_extra,
1270 frozen=frozen,
1271 pattern=pattern,
1272 validate_default=validate_default,
1273 repr=repr,
1274 init=init,
1275 init_var=init_var,
1276 kw_only=kw_only,
1277 coerce_numbers_to_str=coerce_numbers_to_str,
1278 strict=strict,
1279 gt=gt,
1280 ge=ge,
1281 lt=lt,
1282 le=le,
1283 multiple_of=multiple_of,
1284 min_length=min_length,
1285 max_length=max_length,
1286 allow_inf_nan=allow_inf_nan,
1287 max_digits=max_digits,
1288 decimal_places=decimal_places,
1289 union_mode=union_mode,
1290 fail_fast=fail_fast,
1291 )
1294_FIELD_ARG_NAMES = set(inspect.signature(Field).parameters) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1295_FIELD_ARG_NAMES.remove('extra') # do not include the varkwargs parameter 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1298class ModelPrivateAttr(_repr.Representation): 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1299 """A descriptor for private attributes in class models.
1301 !!! warning
1302 You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use
1303 `pydantic.fields.PrivateAttr`. (This is similar to `FieldInfo` vs. `Field`.)
1305 Attributes:
1306 default: The default value of the attribute if not provided.
1307 default_factory: A callable function that generates the default value of the
1308 attribute if not provided.
1309 """
1311 __slots__ = ('default', 'default_factory') 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1313 def __init__( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1314 self, default: Any = PydanticUndefined, *, default_factory: typing.Callable[[], Any] | None = None
1315 ) -> None:
1316 if default is Ellipsis: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1317 self.default = PydanticUndefined 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1318 else:
1319 self.default = default 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1320 self.default_factory = default_factory 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1322 if not typing.TYPE_CHECKING: 1322 ↛ 1334line 1322 didn't jump to line 1334 because the condition on line 1322 was always true1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1323 # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
1325 def __getattr__(self, item: str) -> Any: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1326 """This function improves compatibility with custom descriptors by ensuring delegation happens
1327 as expected when the default value of a private attribute is a descriptor.
1328 """
1329 if item in {'__get__', '__set__', '__delete__'}: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1330 if hasattr(self.default, item): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1331 return getattr(self.default, item) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1332 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1334 def __set_name__(self, cls: type[Any], name: str) -> None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1335 """Preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487."""
1336 default = self.default 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1337 if default is PydanticUndefined: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1338 return 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1339 set_name = getattr(default, '__set_name__', None) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1340 if callable(set_name): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1341 set_name(cls, name) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1343 def get_default(self) -> Any: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1344 """Retrieve the default value of the object.
1346 If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object.
1348 If `self.default_factory` is not `None`, it will call `self.default_factory` and return the value returned.
1350 Returns:
1351 The default value of the object.
1352 """
1353 return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1355 def __eq__(self, other: Any) -> bool: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1356 return isinstance(other, self.__class__) and (self.default, self.default_factory) == ( 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1357 other.default,
1358 other.default_factory,
1359 )
1362# NOTE: Actual return type is 'ModelPrivateAttr', but we want to help type checkers
1363# to understand the magic that happens at runtime.
1364@overload # `default` argument set 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1365def PrivateAttr( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1366 default: _T, 1ghabnijkcdPlmef
1367 *,
1368 init: Literal[False] = False, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1369) -> _T: ... 1ghabnijkcdPlmef
1370@overload # `default_factory` argument set 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1371def PrivateAttr( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1372 *,
1373 default_factory: Callable[[], _T], 1ghabnijkcdPlmef
1374 init: Literal[False] = False, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1375) -> _T: ... 1ghabnijkcdPlmef
1376@overload # No default set 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1377def PrivateAttr( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1378 *,
1379 init: Literal[False] = False, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1380) -> Any: ... 1ghabnijkcdPlmef
1381def PrivateAttr( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1382 default: Any = PydanticUndefined,
1383 *,
1384 default_factory: Callable[[], Any] | None = None,
1385 init: Literal[False] = False,
1386) -> Any:
1387 """!!! abstract "Usage Documentation"
1388 [Private Model Attributes](../concepts/models.md#private-model-attributes)
1390 Indicates that an attribute is intended for private use and not handled during normal validation/serialization.
1392 Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner.
1394 Private attributes are stored in `__private_attributes__` on the model.
1396 Args:
1397 default: The attribute's default value. Defaults to Undefined.
1398 default_factory: Callable that will be
1399 called when a default value is needed for this attribute.
1400 If both `default` and `default_factory` are set, an error will be raised.
1401 init: Whether the attribute should be included in the constructor of the dataclass. Always `False`.
1403 Returns:
1404 An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class.
1406 Raises:
1407 ValueError: If both `default` and `default_factory` are set.
1408 """
1409 if default is not PydanticUndefined and default_factory is not None: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1410 raise TypeError('cannot specify both default and default_factory') 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1412 return ModelPrivateAttr( 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1413 default,
1414 default_factory=default_factory,
1415 )
1418@dataclasses.dataclass(**_internal_dataclass.slots_true) 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1419class ComputedFieldInfo: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1420 """A container for data from `@computed_field` so that we can access it while building the pydantic-core schema.
1422 Attributes:
1423 decorator_repr: A class variable representing the decorator string, '@computed_field'.
1424 wrapped_property: The wrapped computed field property.
1425 return_type: The type of the computed field property's return value.
1426 alias: The alias of the property to be used during serialization.
1427 alias_priority: The priority of the alias. This affects whether an alias generator is used.
1428 title: Title of the computed field to include in the serialization JSON schema.
1429 field_title_generator: A callable that takes a field name and returns title for it.
1430 description: Description of the computed field to include in the serialization JSON schema.
1431 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
1432 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
1433 examples: Example values of the computed field to include in the serialization JSON schema.
1434 json_schema_extra: A dict or callable to provide extra JSON schema properties.
1435 repr: A boolean indicating whether to include the field in the __repr__ output.
1436 """
1438 decorator_repr: ClassVar[str] = '@computed_field' 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1439 wrapped_property: property 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1440 return_type: Any 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1441 alias: str | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1442 alias_priority: int | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1443 title: str | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1444 field_title_generator: Callable[[str, ComputedFieldInfo], str] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1445 description: str | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1446 deprecated: Deprecated | str | bool | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1447 examples: list[Any] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1448 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1449 repr: bool 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1451 @property 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1452 def deprecation_message(self) -> str | None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1453 """The deprecation message to be emitted, or `None` if not set."""
1454 if self.deprecated is None: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1455 return None 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1456 if isinstance(self.deprecated, bool): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1457 return 'deprecated' if self.deprecated else None 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1458 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1460 def _update_from_config(self, config_wrapper: ConfigWrapper, name: str) -> None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1461 """Update the instance from the configuration set on the class this computed field belongs to."""
1462 title_generator = self.field_title_generator or config_wrapper.field_title_generator 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1463 if title_generator is not None and self.title is None: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1464 self.title = title_generator(name, self) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1465 if config_wrapper.alias_generator is not None: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1466 self._apply_alias_generator(config_wrapper.alias_generator, name) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1468 def _apply_alias_generator(self, alias_generator: Callable[[str], str] | AliasGenerator, name: str) -> None: 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1469 """Apply an alias generator to aliases if appropriate.
1471 Args:
1472 alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance.
1473 name: The name of the computed field from which to generate the alias.
1474 """
1475 # Apply an alias_generator if
1476 # 1. An alias is not specified
1477 # 2. An alias is specified, but the priority is <= 1
1479 if self.alias_priority is None or self.alias_priority <= 1 or self.alias is None: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1480 alias, _, serialization_alias = None, None, None 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1482 if isinstance(alias_generator, AliasGenerator): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1483 alias, _, serialization_alias = alias_generator.generate_aliases(name) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1484 elif callable(alias_generator): 1484 ↛ 1490line 1484 didn't jump to line 1490 because the condition on line 1484 was always true1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1485 alias = alias_generator(name) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1487 # if priority is not set, we set to 1
1488 # which supports the case where the alias_generator from a child class is used
1489 # to generate an alias for a field in a parent class
1490 if self.alias_priority is None or self.alias_priority <= 1: 1490 ↛ 1496line 1490 didn't jump to line 1496 because the condition on line 1490 was always true1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1491 self.alias_priority = 1 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1493 # if the priority is 1, then we set the aliases to the generated alias
1494 # note that we use the serialization_alias with priority over alias, as computed_field
1495 # aliases are used for serialization only (not validation)
1496 if self.alias_priority == 1: 1496 ↛ exitline 1496 didn't return from function '_apply_alias_generator' because the condition on line 1496 was always true1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1497 self.alias = _utils.get_first_not_none(serialization_alias, alias) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1500def _wrapped_property_is_private(property_: cached_property | property) -> bool: # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1501 """Returns true if provided property is private, False otherwise."""
1502 wrapped_name: str = '' 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1504 if isinstance(property_, property): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1505 wrapped_name = getattr(property_.fget, '__name__', '') 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1506 elif isinstance(property_, cached_property): # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1507 wrapped_name = getattr(property_.func, '__name__', '') # type: ignore 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1509 return wrapped_name.startswith('_') and not wrapped_name.startswith('__') 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1512# this should really be `property[T], cached_property[T]` but property is not generic unlike cached_property
1513# See https://github.com/python/typing/issues/985 and linked issues
1514PropertyT = typing.TypeVar('PropertyT') 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1517@typing.overload 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1518def computed_field(func: PropertyT, /) -> PropertyT: ... 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1521@typing.overload 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1522def computed_field( 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1523 *,
1524 alias: str | None = None, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1525 alias_priority: int | None = None, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1526 title: str | None = None, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1527 field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1528 description: str | None = None, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1529 deprecated: Deprecated | str | bool | None = None, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1530 examples: list[Any] | None = None, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1531 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1532 repr: bool = True, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1533 return_type: Any = PydanticUndefined, 1JKxyzAghabopqniLMBCDEjkcdrstPNOFGHIlmefuvw
1534) -> typing.Callable[[PropertyT], PropertyT]: ... 1ghabnijkcdPlmef
1537def computed_field( 1JKxyzAghabopqLMBCDEjkcdrstPNOFGHIlmefuvw
1538 func: PropertyT | None = None,
1539 /,
1540 *,
1541 alias: str | None = None,
1542 alias_priority: int | None = None,
1543 title: str | None = None,
1544 field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None,
1545 description: str | None = None,
1546 deprecated: Deprecated | str | bool | None = None,
1547 examples: list[Any] | None = None,
1548 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None,
1549 repr: bool | None = None,
1550 return_type: Any = PydanticUndefined,
1551) -> PropertyT | typing.Callable[[PropertyT], PropertyT]:
1552 """!!! abstract "Usage Documentation"
1553 [The `computed_field` decorator](../concepts/fields.md#the-computed_field-decorator)
1555 Decorator to include `property` and `cached_property` when serializing models or dataclasses.
1557 This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.
1559 ```python
1560 from pydantic import BaseModel, computed_field
1562 class Rectangle(BaseModel):
1563 width: int
1564 length: int
1566 @computed_field
1567 @property
1568 def area(self) -> int:
1569 return self.width * self.length
1571 print(Rectangle(width=3, length=2).model_dump())
1572 #> {'width': 3, 'length': 2, 'area': 6}
1573 ```
1575 If applied to functions not yet decorated with `@property` or `@cached_property`, the function is
1576 automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE,
1577 and confuse static type checkers, thus explicit use of `@property` is recommended.
1579 !!! warning "Mypy Warning"
1580 Even with the `@property` or `@cached_property` applied to your function before `@computed_field`,
1581 mypy may throw a `Decorated property not supported` error.
1582 See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information.
1583 To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line.
1585 [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error.
1587 ```python
1588 import random
1590 from pydantic import BaseModel, computed_field
1592 class Square(BaseModel):
1593 width: float
1595 @computed_field
1596 def area(self) -> float: # converted to a `property` by `computed_field`
1597 return round(self.width**2, 2)
1599 @area.setter
1600 def area(self, new_area: float) -> None:
1601 self.width = new_area**0.5
1603 @computed_field(alias='the magic number', repr=False)
1604 def random_number(self) -> int:
1605 return random.randint(0, 1_000)
1607 square = Square(width=1.3)
1609 # `random_number` does not appear in representation
1610 print(repr(square))
1611 #> Square(width=1.3, area=1.69)
1613 print(square.random_number)
1614 #> 3
1616 square.area = 4
1618 print(square.model_dump_json(by_alias=True))
1619 #> {"width":2.0,"area":4.0,"the magic number":3}
1620 ```
1622 !!! warning "Overriding with `computed_field`"
1623 You can't override a field from a parent class with a `computed_field` in the child class.
1624 `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either.
1625 See the example below:
1627 ```python
1628 from pydantic import BaseModel, computed_field
1630 class Parent(BaseModel):
1631 a: str
1633 try:
1635 class Child(Parent):
1636 @computed_field
1637 @property
1638 def a(self) -> str:
1639 return 'new a'
1641 except TypeError as e:
1642 print(e)
1643 '''
1644 Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
1645 '''
1646 ```
1648 Private properties decorated with `@computed_field` have `repr=False` by default.
1650 ```python
1651 from functools import cached_property
1653 from pydantic import BaseModel, computed_field
1655 class Model(BaseModel):
1656 foo: int
1658 @computed_field
1659 @cached_property
1660 def _private_cached_property(self) -> int:
1661 return -self.foo
1663 @computed_field
1664 @property
1665 def _private_property(self) -> int:
1666 return -self.foo
1668 m = Model(foo=1)
1669 print(repr(m))
1670 #> Model(foo=1)
1671 ```
1673 Args:
1674 func: the function to wrap.
1675 alias: alias to use when serializing this computed field, only used when `by_alias=True`
1676 alias_priority: priority of the alias. This affects whether an alias generator is used
1677 title: Title to use when including this computed field in JSON Schema
1678 field_title_generator: A callable that takes a field name and returns title for it.
1679 description: Description to use when including this computed field in JSON Schema, defaults to the function's
1680 docstring
1681 deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport).
1682 to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the
1683 `deprecated` decorator.
1684 examples: Example values to use when including this computed field in JSON Schema
1685 json_schema_extra: A dict or callable to provide extra JSON schema properties.
1686 repr: whether to include this computed field in model repr.
1687 Default is `False` for private properties and `True` for public properties.
1688 return_type: optional return for serialization logic to expect when serializing to JSON, if included
1689 this must be correct, otherwise a `TypeError` is raised.
1690 If you don't include a return type Any is used, which does runtime introspection to handle arbitrary
1691 objects.
1693 Returns:
1694 A proxy wrapper for the property.
1695 """
1697 def dec(f: Any) -> Any: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1698 nonlocal description, deprecated, return_type, alias_priority
1699 unwrapped = _decorators.unwrap_wrapped_function(f) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1701 if description is None and unwrapped.__doc__: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1702 description = inspect.cleandoc(unwrapped.__doc__) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1704 if deprecated is None and hasattr(unwrapped, '__deprecated__'): 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1705 deprecated = unwrapped.__deprecated__ 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1707 # if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now
1708 f = _decorators.ensure_property(f) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1709 alias_priority = (alias_priority or 2) if alias is not None else None 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1711 if repr is None: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1712 repr_: bool = not _wrapped_property_is_private(property_=f) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1713 else:
1714 repr_ = repr 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1716 dec_info = ComputedFieldInfo( 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1717 f,
1718 return_type,
1719 alias,
1720 alias_priority,
1721 title,
1722 field_title_generator,
1723 description,
1724 deprecated,
1725 examples,
1726 json_schema_extra,
1727 repr_,
1728 )
1729 return _decorators.PydanticDescriptorProxy(f, dec_info) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1731 if func is None: 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1732 return dec 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw
1733 else:
1734 return dec(func) 1JKxyzAghabopqniLMBCDEjkcdrstNOFGHIlmefuvw