Coverage for pydantic/fields.py: 91.23%

488 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-07-01 21:48 +0000

1"""Defining fields on models.""" 

2 

3from __future__ import annotations as _annotations 1DErstujkabcqlFGvwxymndefJHIzABCopghi

4 

5import dataclasses 1DErstujkabcqlFGvwxymndefJHIzABCopghi

6import inspect 1DErstujkabcqlFGvwxymndefJHIzABCopghi

7import sys 1DErstujkabcqlFGvwxymndefJHIzABCopghi

8import typing 1DErstujkabcqlFGvwxymndefJHIzABCopghi

9from collections.abc import Callable, Mapping 1DErstujkabcqlFGvwxymndefJHIzABCopghi

10from copy import copy 1DErstujkabcqlFGvwxymndefJHIzABCopghi

11from dataclasses import Field as DataclassField 1DErstujkabcqlFGvwxymndefJHIzABCopghi

12from functools import cached_property 1DErstujkabcqlFGvwxymndefJHIzABCopghi

13from typing import Annotated, Any, ClassVar, Literal, TypeVar, cast, final, overload 1DErstujkabcqlFGvwxymndefJHIzABCopghi

14from warnings import warn 1DErstujkabcqlFGvwxymndefJHIzABCopghi

15 

16import annotated_types 1DErstujkabcqlFGvwxymndefJHIzABCopghi

17import typing_extensions 1DErstujkabcqlFGvwxymndefJHIzABCopghi

18from pydantic_core import PydanticUndefined 1DErstujkabcqlFGvwxymndefJHIzABCopghi

19from typing_extensions import Self, TypeAlias, Unpack, deprecated 1DErstujkabcqlFGvwxymndefJHIzABCopghi

20from typing_inspection import typing_objects 1DErstujkabcqlFGvwxymndefJHIzABCopghi

21from typing_inspection.introspection import UNKNOWN, AnnotationSource, ForbiddenQualifier, Qualifier, inspect_annotation 1DErstujkabcqlFGvwxymndefJHIzABCopghi

22 

23from . import types 1DErstujkabcqlFGvwxymndefJHIzABCopghi

24from ._internal import _decorators, _fields, _generics, _internal_dataclass, _repr, _typing_extra, _utils 1DErstujkabcqlFGvwxymndefJHIzABCopghi

25from ._internal._namespace_utils import GlobalsNamespace, MappingNamespace 1DErstujkabcqlFGvwxymndefJHIzABCopghi

26from .aliases import AliasChoices, AliasGenerator, AliasPath 1DErstujkabcqlFGvwxymndefJHIzABCopghi

27from .config import JsonDict 1DErstujkabcqlFGvwxymndefJHIzABCopghi

28from .errors import PydanticForbiddenQualifier, PydanticUserError 1DErstujkabcqlFGvwxymndefJHIzABCopghi

29from .json_schema import PydanticJsonSchemaWarning 1DErstujkabcqlFGvwxymndefJHIzABCopghi

30from .warnings import PydanticDeprecatedSince20 1DErstujkabcqlFGvwxymndefJHIzABCopghi

31 

32if typing.TYPE_CHECKING: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

33 from ._internal._config import ConfigWrapper 

34 from ._internal._repr import ReprArgs 1l

35else: 

36 # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 

37 # and https://youtrack.jetbrains.com/issue/PY-51428 

38 DeprecationWarning = PydanticDeprecatedSince20 1DErstujkabcqlFGvwxymndefJHIzABCopghi

39 

40__all__ = 'Field', 'PrivateAttr', 'computed_field' 1DErstujkabcqlFGvwxymndefJHIzABCopghi

41 

42 

43_Unset: Any = PydanticUndefined 1DErstujkabcqlFGvwxymndefJHIzABCopghi

44 

45if sys.version_info >= (3, 13): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

46 import warnings 1abcdefJghi

47 

48 Deprecated: TypeAlias = warnings.deprecated | deprecated 1abcdefJghi

49else: 

50 Deprecated: TypeAlias = deprecated 1DErstujkqlFGvwxymnHIzABCop

51 

52 

53class _FromFieldInfoInputs(typing_extensions.TypedDict, total=False): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

54 """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.from_field`.""" 

55 

56 # TODO PEP 747: use TypeForm: 

57 annotation: type[Any] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

58 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

59 alias: str | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

60 alias_priority: int | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

61 validation_alias: str | AliasPath | AliasChoices | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

62 serialization_alias: str | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

63 title: str | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

64 field_title_generator: Callable[[str, FieldInfo], str] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

65 description: str | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

66 examples: list[Any] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

67 exclude: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

68 gt: annotated_types.SupportsGt | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

69 ge: annotated_types.SupportsGe | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

70 lt: annotated_types.SupportsLt | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

71 le: annotated_types.SupportsLe | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

72 multiple_of: float | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

73 strict: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

74 min_length: int | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

75 max_length: int | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

76 pattern: str | typing.Pattern[str] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

77 allow_inf_nan: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

78 max_digits: int | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

79 decimal_places: int | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

80 union_mode: Literal['smart', 'left_to_right'] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

81 discriminator: str | types.Discriminator | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

82 deprecated: Deprecated | str | bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

83 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

84 frozen: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

85 validate_default: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

86 repr: bool 1DErstujkabcqlFGvwxymndefJHIzABCopghi

87 init: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

88 init_var: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

89 kw_only: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

90 coerce_numbers_to_str: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

91 fail_fast: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

92 

93 

94class _FieldInfoInputs(_FromFieldInfoInputs, total=False): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

95 """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.__init__`.""" 

96 

97 default: Any 1DErstujkabcqlFGvwxymndefJHIzABCopghi

98 

99 

100@final 1DErstujkabcqlFGvwxymndefJHIzABCopghi

101class FieldInfo(_repr.Representation): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

102 """This class holds information about a field. 

103 

104 `FieldInfo` is used for any field definition regardless of whether the [`Field()`][pydantic.fields.Field] 

105 function is explicitly used. 

106 

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. 

110 

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 """ 

137 

138 annotation: type[Any] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

139 default: Any 1DErstujkabcqlFGvwxymndefJHIzABCopghi

140 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

141 alias: str | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

142 alias_priority: int | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

143 validation_alias: str | AliasPath | AliasChoices | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

144 serialization_alias: str | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

145 title: str | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

146 field_title_generator: Callable[[str, FieldInfo], str] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

147 description: str | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

148 examples: list[Any] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

149 exclude: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

150 discriminator: str | types.Discriminator | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

151 deprecated: Deprecated | str | bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

152 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

153 frozen: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

154 validate_default: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

155 repr: bool 1DErstujkabcqlFGvwxymndefJHIzABCopghi

156 init: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

157 init_var: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

158 kw_only: bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

159 metadata: list[Any] 1DErstujkabcqlFGvwxymndefJHIzABCopghi

160 

161 __slots__ = ( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

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 ) 

190 

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]] = { 1DErstujkabcqlFGvwxymndefJHIzABCopghi

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 } 

210 

211 def __init__(self, **kwargs: Unpack[_FieldInfoInputs]) -> None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

212 """This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function 

213 or one of the constructor classmethods. 

214 

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} 1DErstujkabcqlFGvwxymndefJHIzABCopghi

218 kwargs = {k: _DefaultValues.get(k) if v is _Unset else v for k, v in kwargs.items()} # type: ignore 1DErstujkabcqlFGvwxymndefJHIzABCopghi

219 self.annotation = kwargs.get('annotation') 1DErstujkabcqlFGvwxymndefJHIzABCopghi

220 

221 default = kwargs.pop('default', PydanticUndefined) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

222 if default is Ellipsis: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

223 self.default = PydanticUndefined 1DErstujkabcqlFGvwxymndefJHIzABCopghi

224 self._attributes_set.pop('default', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

225 else: 

226 self.default = default 1DErstujkabcqlFGvwxymndefJHIzABCopghi

227 

228 self.default_factory = kwargs.pop('default_factory', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

229 

230 if self.default is not PydanticUndefined and self.default_factory is not None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

231 raise TypeError('cannot specify both default and default_factory') 1DErstujkabcqlFGvwxymndefHIzABCopghi

232 

233 self.alias = kwargs.pop('alias', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

234 self.validation_alias = kwargs.pop('validation_alias', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

235 self.serialization_alias = kwargs.pop('serialization_alias', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

236 alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias)) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

237 self.alias_priority = kwargs.pop('alias_priority', None) or 2 if alias_is_set else None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

238 self.title = kwargs.pop('title', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

239 self.field_title_generator = kwargs.pop('field_title_generator', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

240 self.description = kwargs.pop('description', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

241 self.examples = kwargs.pop('examples', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

242 self.exclude = kwargs.pop('exclude', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

243 self.discriminator = kwargs.pop('discriminator', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

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)) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

246 self.repr = kwargs.pop('repr', True) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

247 self.json_schema_extra = kwargs.pop('json_schema_extra', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

248 self.validate_default = kwargs.pop('validate_default', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

249 self.frozen = kwargs.pop('frozen', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

250 # currently only used on dataclasses 

251 self.init = kwargs.pop('init', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

252 self.init_var = kwargs.pop('init_var', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

253 self.kw_only = kwargs.pop('kw_only', None) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

254 

255 self.metadata = self._collect_metadata(kwargs) # type: ignore 1DErstujkabcqlFGvwxymndefJHIzABCopghi

256 

257 # Private attributes: 

258 self._qualifiers: set[Qualifier] = set() 1DErstujkabcqlFGvwxymndefJHIzABCopghi

259 # Used to rebuild FieldInfo instances: 

260 self._complete = True 1DErstujkabcqlFGvwxymndefJHIzABCopghi

261 self._original_annotation: Any = PydanticUndefined 1DErstujkabcqlFGvwxymndefJHIzABCopghi

262 self._original_assignment: Any = PydanticUndefined 1DErstujkabcqlFGvwxymndefJHIzABCopghi

263 

264 @staticmethod 1DErstujkabcqlFGvwxymndefJHIzABCopghi

265 def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

266 """Create a new `FieldInfo` object with the `Field` function. 

267 

268 Args: 

269 default: The default value for the field. Defaults to Undefined. 

270 **kwargs: Additional arguments dictionary. 

271 

272 Raises: 

273 TypeError: If 'annotation' is passed as a keyword argument. 

274 

275 Returns: 

276 A new FieldInfo object with the given parameters. 

277 

278 Example: 

279 This is how you can create a field with default value like this: 

280 

281 ```python 

282 import pydantic 

283 

284 class MyModel(pydantic.BaseModel): 

285 foo: int = pydantic.Field(4) 

286 ``` 

287 """ 

288 if 'annotation' in kwargs: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

289 raise TypeError('"annotation" is not permitted as a Field keyword argument') 1DErstujkabcqlFGvwxymndefHIzABCopghi

290 return FieldInfo(default=default, **kwargs) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

291 

292 @staticmethod 1DErstujkabcqlFGvwxymndefJHIzABCopghi

293 def from_annotation(annotation: type[Any], *, _source: AnnotationSource = AnnotationSource.ANY) -> FieldInfo: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

294 """Creates a `FieldInfo` instance from a bare annotation. 

295 

296 This function is used internally to create a `FieldInfo` from a bare annotation like this: 

297 

298 ```python 

299 import pydantic 

300 

301 class MyModel(pydantic.BaseModel): 

302 foo: int # <-- like this 

303 ``` 

304 

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.: 

307 

308 ```python 

309 from typing import Annotated 

310 

311 import annotated_types 

312 

313 import pydantic 

314 

315 class MyModel(pydantic.BaseModel): 

316 foo: Annotated[int, annotated_types.Gt(42)] 

317 bar: Annotated[int, pydantic.Field(gt=42)] 

318 ``` 

319 

320 Args: 

321 annotation: An annotation object. 

322 

323 Returns: 

324 An instance of the field metadata. 

325 """ 

326 try: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

327 inspected_ann = inspect_annotation( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

328 annotation, 

329 annotation_source=_source, 

330 unpack_type_aliases='skip', 

331 ) 

332 except ForbiddenQualifier as e: 1DErstujkabcqlFGvwxymndefHIzABCopghi

333 raise PydanticForbiddenQualifier(e.qualifier, annotation) 1DErstujkabcqlFGvwxymndefHIzABCopghi

334 

335 # TODO check for classvar and error? 

336 

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 1DErstujkabcqlFGvwxymndefJHIzABCopghi

341 final = 'final' in inspected_ann.qualifiers 1DErstujkabcqlFGvwxymndefJHIzABCopghi

342 metadata = inspected_ann.metadata 1DErstujkabcqlFGvwxymndefJHIzABCopghi

343 

344 attr_overrides = {'annotation': type_expr} 1DErstujkabcqlFGvwxymndefJHIzABCopghi

345 if final: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

346 attr_overrides['frozen'] = True 1DErstujkabcqlFGvwxymndefHIzABCopghi

347 field_info = FieldInfo._construct(metadata, **attr_overrides) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

348 field_info._qualifiers = inspected_ann.qualifiers 1DErstujkabcqlFGvwxymndefJHIzABCopghi

349 return field_info 1DErstujkabcqlFGvwxymndefJHIzABCopghi

350 

351 @staticmethod 1DErstujkabcqlFGvwxymndefJHIzABCopghi

352 def from_annotated_attribute( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

353 annotation: type[Any], default: Any, *, _source: AnnotationSource = AnnotationSource.ANY 

354 ) -> FieldInfo: 

355 """Create `FieldInfo` from an annotation with a default value. 

356 

357 This is used in cases like the following: 

358 

359 ```python 

360 from typing import Annotated 

361 

362 import annotated_types 

363 

364 import pydantic 

365 

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 ``` 

371 

372 Args: 

373 annotation: The type annotation of the field. 

374 default: The default value of the field. 

375 

376 Returns: 

377 A field object with the passed values. 

378 """ 

379 if annotation is default: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

380 raise PydanticUserError( 1DErstujkabcqlFGvwxymndefHIzABCopghi

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 ) 

385 

386 try: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

387 inspected_ann = inspect_annotation( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

388 annotation, 

389 annotation_source=_source, 

390 unpack_type_aliases='skip', 

391 ) 

392 except ForbiddenQualifier as e: 1DErstujkabcqlFGvwxymndefHIzABCopghi

393 raise PydanticForbiddenQualifier(e.qualifier, annotation) 1DErstujkabcqlFGvwxymndefHIzABCopghi

394 

395 # TODO check for classvar and error? 

396 

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 1DErstujkabcqlFGvwxymndefJHIzABCopghi

400 final = 'final' in inspected_ann.qualifiers 1DErstujkabcqlFGvwxymndefJHIzABCopghi

401 metadata = inspected_ann.metadata 1DErstujkabcqlFGvwxymndefJHIzABCopghi

402 

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 1DErstujkabcqlFGvwxymndefJHIzABCopghi

407 attr_overrides = {'annotation': type_expr} 1DErstujkabcqlFGvwxymndefJHIzABCopghi

408 if final: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

409 attr_overrides['frozen'] = True 1DErstujkabcqlFGvwxymndefHIzABCopghi

410 

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: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

415 field_info = default._copy() 1DErstujkabcqlFGvwxymndefHIzABCopghi

416 field_info._attributes_set.update(attr_overrides) 1DErstujkabcqlFGvwxymndefHIzABCopghi

417 for k, v in attr_overrides.items(): 1DErstujkabcqlFGvwxymndefHIzABCopghi

418 setattr(field_info, k, v) 1DErstujkabcqlFGvwxymndefHIzABCopghi

419 return field_info 1DErstujkabcqlFGvwxymndefHIzABCopghi

420 

421 if isinstance(default, FieldInfo): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

422 default_copy = default._copy() # Copy unnecessary when we remove HACK 1. 1DErstujkabcqlFGvwxymndefJHIzABCopghi

423 prepend_metadata = default_copy.metadata 1DErstujkabcqlFGvwxymndefJHIzABCopghi

424 default_copy.metadata = [] 1DErstujkabcqlFGvwxymndefJHIzABCopghi

425 metadata = metadata + [default_copy] 1DErstujkabcqlFGvwxymndefJHIzABCopghi

426 elif isinstance(default, dataclasses.Field): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

427 from_field = FieldInfo._from_dataclass_field(default) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

428 prepend_metadata = from_field.metadata # Unnecessary when we remove HACK 1. 1DErstujkabcqlFGvwxymndefJHIzABCopghi

429 from_field.metadata = [] 1DErstujkabcqlFGvwxymndefJHIzABCopghi

430 metadata = metadata + [from_field] 1DErstujkabcqlFGvwxymndefJHIzABCopghi

431 if 'init_var' in inspected_ann.qualifiers: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

432 attr_overrides['init_var'] = True 1DErstujkabcqlFGvwxymndefJHIzABCopghi

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 true1DErstujkabcqlFGvwxymndefJHIzABCopghi

434 attr_overrides['init'] = init 1DErstujkabcqlFGvwxymndefJHIzABCopghi

435 if (kw_only := getattr(default, 'kw_only', None)) is not None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

436 attr_overrides['kw_only'] = kw_only 1rstujkabclvwxymndefJzABCopghi

437 else: 

438 # `default` is the actual default value 

439 attr_overrides['default'] = default 1DErstujkabcqlFGvwxymndefJHIzABCopghi

440 

441 field_info = FieldInfo._construct( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

442 prepend_metadata + metadata if prepend_metadata is not None else metadata, **attr_overrides 

443 ) 

444 field_info._qualifiers = inspected_ann.qualifiers 1DErstujkabcqlFGvwxymndefJHIzABCopghi

445 return field_info 1DErstujkabcqlFGvwxymndefJHIzABCopghi

446 

447 @classmethod 1DErstujkabcqlFGvwxymndefJHIzABCopghi

448 def _construct(cls, metadata: list[Any], **attr_overrides: Any) -> Self: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

449 """Construct the final `FieldInfo` instance, by merging the possibly existing `FieldInfo` instances from the metadata. 

450 

451 With the following example: 

452 

453 ```python {test="skip" lint="skip"} 

454 class Model(BaseModel): 

455 f: Annotated[int, Gt(1), Field(description='desc', lt=2)] 

456 ``` 

457 

458 `metadata` refers to the metadata elements of the `Annotated` form. This metadata is iterated over from left to right: 

459 

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. 

465 

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. 

471 

472 Returns: 

473 The final merged `FieldInfo` instance. 

474 """ 

475 merged_metadata: list[Any] = [] 1DErstujkabcqlFGvwxymndefJHIzABCopghi

476 merged_kwargs: dict[str, Any] = {} 1DErstujkabcqlFGvwxymndefJHIzABCopghi

477 

478 for meta in metadata: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

479 if isinstance(meta, FieldInfo): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

480 merged_metadata.extend(meta.metadata) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

481 

482 new_js_extra: JsonDict | None = None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

483 current_js_extra = meta.json_schema_extra 1DErstujkabcqlFGvwxymndefJHIzABCopghi

484 if current_js_extra is not None and 'json_schema_extra' in merged_kwargs: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

485 # We need to merge `json_schema_extra`'s: 

486 existing_js_extra = merged_kwargs['json_schema_extra'] 1DErstujkabcqlFGvwxymndefHIzABCopghi

487 if isinstance(existing_js_extra, dict): 1DErstujkabcqlFGvwxymndefHIzABCopghi

488 if isinstance(current_js_extra, dict): 1DErstujkabcqlFGvwxymndefHIzABCopghi

489 new_js_extra = { 1DErstujkabcqlFGvwxymndefHIzABCopghi

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 true1DErstujkabcqlFGvwxymndefHIzABCopghi

494 warn( 1DErstujkabcqlFGvwxymndefHIzABCopghi

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 true1DErstujkabcqlFGvwxymndefHIzABCopghi

501 warn( 1DErstujkabcqlFGvwxymndefHIzABCopghi

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 ) 

507 

508 merged_kwargs.update(meta._attributes_set) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

509 if new_js_extra is not None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

510 merged_kwargs['json_schema_extra'] = new_js_extra 1DErstujkabcqlFGvwxymndefHIzABCopghi

511 elif typing_objects.is_deprecated(meta): 1DErstujkabcqlFGvwxymndefHIzABCopghi

512 merged_kwargs['deprecated'] = meta 1DErstujkabcqlFGvwxymndefHIzABCopghi

513 else: 

514 merged_metadata.append(meta) 1DErstujkabcqlFGvwxymndefHIzABCopghi

515 

516 merged_kwargs.update(attr_overrides) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

517 merged_field_info = cls(**merged_kwargs) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

518 merged_field_info.metadata = merged_metadata 1DErstujkabcqlFGvwxymndefJHIzABCopghi

519 return merged_field_info 1DErstujkabcqlFGvwxymndefJHIzABCopghi

520 

521 @staticmethod 1DErstujkabcqlFGvwxymndefJHIzABCopghi

522 @typing_extensions.deprecated( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

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: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

528 """Merge `FieldInfo` instances keeping only explicitly set attributes. 

529 

530 Later `FieldInfo` instances override earlier ones. 

531 

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 true1DErstujkabcqlFGvwxymndefHIzABCopghi

536 # No merging necessary, but we still need to make a copy and apply the overrides 

537 field_info = field_infos[0]._copy() 1DErstujkabcqlFGvwxymndefHIzABCopghi

538 field_info._attributes_set.update(overrides) 1DErstujkabcqlFGvwxymndefHIzABCopghi

539 

540 default_override = overrides.pop('default', PydanticUndefined) 1DErstujkabcqlFGvwxymndefHIzABCopghi

541 if default_override is Ellipsis: 541 ↛ 542line 541 didn't jump to line 542 because the condition on line 541 was never true1DErstujkabcqlFGvwxymndefHIzABCopghi

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 true1DErstujkabcqlFGvwxymndefHIzABCopghi

544 field_info.default = default_override 1DErstujkabcqlFGvwxymndefHIzABCopghi

545 

546 for k, v in overrides.items(): 546 ↛ 547line 546 didn't jump to line 547 because the loop on line 546 never started1DErstujkabcqlFGvwxymndefHIzABCopghi

547 setattr(field_info, k, v) 

548 return field_info # type: ignore 1DErstujkabcqlFGvwxymndefHIzABCopghi

549 

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() 

554 

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') 

558 

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 

579 

580 # later FieldInfo instances override everything except json_schema_extra from earlier FieldInfo instances 

581 merged_field_info_kwargs.update(attributes_set) 

582 

583 for x in field_info.metadata: 

584 if not isinstance(x, FieldInfo): 

585 metadata[type(x)] = x 

586 

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 

591 

592 @staticmethod 1DErstujkabcqlFGvwxymndefJHIzABCopghi

593 def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

594 """Return a new `FieldInfo` instance from a `dataclasses.Field` instance. 

595 

596 Args: 

597 dc_field: The `dataclasses.Field` instance to convert. 

598 

599 Returns: 

600 The corresponding `FieldInfo` instance. 

601 

602 Raises: 

603 TypeError: If any of the `FieldInfo` kwargs does not match the `dataclass.Field` kwargs. 

604 """ 

605 default = dc_field.default 1DErstujkabcqlFGvwxymndefJHIzABCopghi

606 if default is dataclasses.MISSING: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

607 default = _Unset 1DErstujkabcqlFGvwxymndefJHIzABCopghi

608 

609 if dc_field.default_factory is dataclasses.MISSING: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

610 default_factory = _Unset 1DErstujkabcqlFGvwxymndefJHIzABCopghi

611 else: 

612 default_factory = dc_field.default_factory 1DErstujkabcqlFGvwxymndefHIzABCopghi

613 

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} 1DErstujkabcqlFGvwxymndefJHIzABCopghi

616 return Field(default=default, default_factory=default_factory, repr=dc_field.repr, **dc_field_metadata) # pyright: ignore[reportCallIssue] 1DErstujkabcqlFGvwxymndefJHIzABCopghi

617 

618 @staticmethod 1DErstujkabcqlFGvwxymndefJHIzABCopghi

619 def _collect_metadata(kwargs: dict[str, Any]) -> list[Any]: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

620 """Collect annotations from kwargs. 

621 

622 Args: 

623 kwargs: Keyword arguments passed to the function. 

624 

625 Returns: 

626 A list of metadata objects - a combination of `annotated_types.BaseMetadata` and 

627 `PydanticMetadata`. 

628 """ 

629 metadata: list[Any] = [] 1DErstujkabcqlFGvwxymndefJHIzABCopghi

630 general_metadata = {} 1DErstujkabcqlFGvwxymndefJHIzABCopghi

631 for key, value in list(kwargs.items()): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

632 try: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

633 marker = FieldInfo.metadata_lookup[key] 1DErstujkabcqlFGvwxymndefJHIzABCopghi

634 except KeyError: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

635 continue 1DErstujkabcqlFGvwxymndefJHIzABCopghi

636 

637 del kwargs[key] 1DErstujkabcqlFGvwxymndefJHIzABCopghi

638 if value is not None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

639 if marker is None: 1DErstujkabcqlFGvwxymndefHIzABCopghi

640 general_metadata[key] = value 1DErstujkabcqlFGvwxymndefHIzABCopghi

641 else: 

642 metadata.append(marker(value)) 1DErstujkabcqlFGvwxymndefHIzABCopghi

643 if general_metadata: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

644 metadata.append(_fields.pydantic_general_metadata(**general_metadata)) 1DErstujkabcqlFGvwxymndefHIzABCopghi

645 return metadata 1DErstujkabcqlFGvwxymndefJHIzABCopghi

646 

647 @property 1DErstujkabcqlFGvwxymndefJHIzABCopghi

648 def deprecation_message(self) -> str | None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

649 """The deprecation message to be emitted, or `None` if not set.""" 

650 if self.deprecated is None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

651 return None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

652 if isinstance(self.deprecated, bool): 1DErstujkabcqlFGvwxymndefHIzABCopghi

653 return 'deprecated' if self.deprecated else None 1DErstujkabcqlFGvwxymndefHIzABCopghi

654 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1DErstujkabcqlFGvwxymndefHIzABCopghi

655 

656 @property 1DErstujkabcqlFGvwxymndefJHIzABCopghi

657 def default_factory_takes_validated_data(self) -> bool | None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

658 """Whether the provided default factory callable has a validated data parameter. 

659 

660 Returns `None` if no default factory is set. 

661 """ 

662 if self.default_factory is not None: 662 ↛ exitline 662 didn't return from function 'default_factory_takes_validated_data' because the condition on line 662 was always true1DErstujkabcqlFGvwxymndefHIzABCopghi

663 return _fields.takes_validated_data_argument(self.default_factory) 1DErstujkabcqlFGvwxymndefHIzABCopghi

664 

665 @overload 1DErstujkabcqlFGvwxymndefJHIzABCopghi

666 def get_default( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

667 self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

668 ) -> Any: ... 1jkabcqlmndefJopghi

669 

670 @overload 1DErstujkabcqlFGvwxymndefJHIzABCopghi

671 def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ... 1DErstujkabcqlFGvwxymndefJHIzABCopghi

672 

673 def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

674 """Get the default value. 

675 

676 We expose an option for whether to call the default_factory (if present), as calling it may 

677 result in side effects that we want to avoid. However, there are times when it really should 

678 be called (namely, when instantiating a model via `model_construct`). 

679 

680 Args: 

681 call_default_factory: Whether to call the default factory or not. 

682 validated_data: The already validated data to be passed to the default factory. 

683 

684 Returns: 

685 The default value, calling the default factory if requested or `None` if not set. 

686 """ 

687 if self.default_factory is None: 1DErstujkabcqlFGvwxymndefHIzABCopghi

688 return _utils.smart_deepcopy(self.default) 1DErstujkabcqlFGvwxymndefHIzABCopghi

689 elif call_default_factory: 689 ↛ 701line 689 didn't jump to line 701 because the condition on line 689 was always true1DErstujkabcqlFGvwxymndefHIzABCopghi

690 if self.default_factory_takes_validated_data: 1DErstujkabcqlFGvwxymndefHIzABCopghi

691 fac = cast('Callable[[dict[str, Any]], Any]', self.default_factory) 1DErstujkabcqlFGvwxymndefHIzABCopghi

692 if validated_data is None: 692 ↛ 693line 692 didn't jump to line 693 because the condition on line 692 was never true1DErstujkabcqlFGvwxymndefHIzABCopghi

693 raise ValueError( 

694 "The default factory requires the 'validated_data' argument, which was not provided when calling 'get_default'." 

695 ) 

696 return fac(validated_data) 1DErstujkabcqlFGvwxymndefHIzABCopghi

697 else: 

698 fac = cast('Callable[[], Any]', self.default_factory) 1DErstujkabcqlFGvwxymndefHIzABCopghi

699 return fac() 1DErstujkabcqlFGvwxymndefHIzABCopghi

700 else: 

701 return None 

702 

703 def is_required(self) -> bool: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

704 """Check if the field is required (i.e., does not have a default value or factory). 

705 

706 Returns: 

707 `True` if the field is required, `False` otherwise. 

708 """ 

709 return self.default is PydanticUndefined and self.default_factory is None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

710 

711 def rebuild_annotation(self) -> Any: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

712 """Attempts to rebuild the original annotation for use in function signatures. 

713 

714 If metadata is present, it adds it to the original annotation using 

715 `Annotated`. Otherwise, it returns the original annotation as-is. 

716 

717 Note that because the metadata has been flattened, the original annotation 

718 may not be reconstructed exactly as originally provided, e.g. if the original 

719 type had unrecognized annotations, or was annotated with a call to `pydantic.Field`. 

720 

721 Returns: 

722 The rebuilt annotation. 

723 """ 

724 if not self.metadata: 1DErstujkabcqlFGvwxymndefHIzABCopghi

725 return self.annotation 1DErstujkabcqlFGvwxymndefHIzABCopghi

726 else: 

727 # Annotated arguments must be a tuple 

728 return Annotated[(self.annotation, *self.metadata)] # type: ignore 1DErstujkabcqlFGvwxymndefHIzABCopghi

729 

730 def apply_typevars_map( 1DErstujkabcFGvwxymndefJHIzABCopghi

731 self, 

732 typevars_map: Mapping[TypeVar, Any] | None, 

733 globalns: GlobalsNamespace | None = None, 

734 localns: MappingNamespace | None = None, 

735 ) -> None: 

736 """Apply a `typevars_map` to the annotation. 

737 

738 This method is used when analyzing parametrized generic types to replace typevars with their concrete types. 

739 

740 This method applies the `typevars_map` to the annotation in place. 

741 

742 Args: 

743 typevars_map: A dictionary mapping type variables to their concrete types. 

744 globalns: The globals namespace to use during type annotation evaluation. 

745 localns: The locals namespace to use during type annotation evaluation. 

746 

747 See Also: 

748 pydantic._internal._generics.replace_types is used for replacing the typevars with 

749 their concrete types. 

750 """ 

751 annotation = _generics.replace_types(self.annotation, typevars_map) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

752 annotation, evaluated = _typing_extra.try_eval_type(annotation, globalns, localns) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

753 self.annotation = annotation 1DErstujkabcqlFGvwxymndefJHIzABCopghi

754 if not evaluated: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

755 self._complete = False 1DErstujkabcqlFGvwxymndefHIzABCopghi

756 self._original_annotation = self.annotation 1DErstujkabcqlFGvwxymndefHIzABCopghi

757 

758 def _copy(self) -> Self: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

759 """Return a copy of the `FieldInfo` instance.""" 

760 # Note: we can't define a custom `__copy__()`, as `FieldInfo` is being subclassed 

761 # by some third-party libraries with extra attributes defined (and as `FieldInfo` 

762 # is slotted, we can't make a copy of the `__dict__`). 

763 copied = copy(self) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

764 for attr_name in ('metadata', '_attributes_set', '_qualifiers'): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

765 # Apply "deep-copy" behavior on collections attributes: 

766 value = getattr(copied, attr_name).copy() 1DErstujkabcqlFGvwxymndefJHIzABCopghi

767 setattr(copied, attr_name, value) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

768 

769 return copied 1DErstujkabcqlFGvwxymndefJHIzABCopghi

770 

771 def __repr_args__(self) -> ReprArgs: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

772 yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation)) 1DErstujkabcqlFGvwxymndefHIzABCopghi

773 yield 'required', self.is_required() 1DErstujkabcqlFGvwxymndefHIzABCopghi

774 

775 for s in self.__slots__: 1DErstujkabcqlFGvwxymndefHIzABCopghi

776 # TODO: properly make use of the protocol (https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol) 

777 # By yielding a three-tuple: 

778 if s in ( 1DErstujkabcqlFGvwxymndefHIzABCopghi

779 'annotation', 

780 '_attributes_set', 

781 '_qualifiers', 

782 '_complete', 

783 '_original_assignment', 

784 '_original_annotation', 

785 ): 

786 continue 1DErstujkabcqlFGvwxymndefHIzABCopghi

787 elif s == 'metadata' and not self.metadata: 1DErstujkabcqlFGvwxymndefHIzABCopghi

788 continue 1DErstujkabcqlFGvwxymndefHIzABCopghi

789 elif s == 'repr' and self.repr is True: 1DErstujkabcqlFGvwxymndefHIzABCopghi

790 continue 1DErstujkabcqlFGvwxymndefHIzABCopghi

791 if s == 'frozen' and self.frozen is False: 1DErstujkabcqlFGvwxymndefHIzABCopghi

792 continue 1DErstujkabcqlFGvwxymndefHIzABCopghi

793 if s == 'validation_alias' and self.validation_alias == self.alias: 1DErstujkabcqlFGvwxymndefHIzABCopghi

794 continue 1DErstujkabcqlFGvwxymndefHIzABCopghi

795 if s == 'serialization_alias' and self.serialization_alias == self.alias: 1DErstujkabcqlFGvwxymndefHIzABCopghi

796 continue 1DErstujkabcqlFGvwxymndefHIzABCopghi

797 if s == 'default' and self.default is not PydanticUndefined: 1DErstujkabcqlFGvwxymndefHIzABCopghi

798 yield 'default', self.default 1DErstujkabcqlFGvwxymndefHIzABCopghi

799 elif s == 'default_factory' and self.default_factory is not None: 1DErstujkabcqlFGvwxymndefHIzABCopghi

800 yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory)) 1DErstujkabcqlFGvwxymndefHIzABCopghi

801 else: 

802 value = getattr(self, s) 1DErstujkabcqlFGvwxymndefHIzABCopghi

803 if value is not None and value is not PydanticUndefined: 1DErstujkabcqlFGvwxymndefHIzABCopghi

804 yield s, value 1DErstujkabcqlFGvwxymndefHIzABCopghi

805 

806 

807class _EmptyKwargs(typing_extensions.TypedDict): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

808 """This class exists solely to ensure that type checking warns about passing `**extra` in `Field`.""" 

809 

810 

811_DefaultValues = { 1DErstujkabcqlFGvwxymndefJHIzABCopghi

812 'default': ..., 

813 'default_factory': None, 

814 'alias': None, 

815 'alias_priority': None, 

816 'validation_alias': None, 

817 'serialization_alias': None, 

818 'title': None, 

819 'description': None, 

820 'examples': None, 

821 'exclude': None, 

822 'discriminator': None, 

823 'json_schema_extra': None, 

824 'frozen': None, 

825 'validate_default': None, 

826 'repr': True, 

827 'init': None, 

828 'init_var': None, 

829 'kw_only': None, 

830 'pattern': None, 

831 'strict': None, 

832 'gt': None, 

833 'ge': None, 

834 'lt': None, 

835 'le': None, 

836 'multiple_of': None, 

837 'allow_inf_nan': None, 

838 'max_digits': None, 

839 'decimal_places': None, 

840 'min_length': None, 

841 'max_length': None, 

842 'coerce_numbers_to_str': None, 

843} 

844 

845 

846_T = TypeVar('_T') 1DErstujkabcqlFGvwxymndefJHIzABCopghi

847 

848 

849# NOTE: Actual return type is 'FieldInfo', but we want to help type checkers 

850# to understand the magic that happens at runtime with the following overloads: 

851@overload # type hint the return value as `Any` to avoid type checking regressions when using `...`. 1DErstujkabcqlFGvwxymndefJHIzABCopghi

852def Field( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

853 default: ellipsis, # noqa: F821 # TODO: use `_typing_extra.EllipsisType` when we drop Py3.9 1jkabcqlmndefJopghi

854 *, 

855 alias: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

856 alias_priority: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

857 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

858 serialization_alias: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

859 title: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

860 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

861 description: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

862 examples: list[Any] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

863 exclude: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

864 discriminator: str | types.Discriminator | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

865 deprecated: Deprecated | str | bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

866 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

867 frozen: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

868 validate_default: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

869 repr: bool = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

870 init: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

871 init_var: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

872 kw_only: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

873 pattern: str | typing.Pattern[str] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

874 strict: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

875 coerce_numbers_to_str: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

876 gt: annotated_types.SupportsGt | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

877 ge: annotated_types.SupportsGe | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

878 lt: annotated_types.SupportsLt | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

879 le: annotated_types.SupportsLe | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

880 multiple_of: float | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

881 allow_inf_nan: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

882 max_digits: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

883 decimal_places: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

884 min_length: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

885 max_length: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

886 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

887 fail_fast: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

888 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefJopghi

889) -> Any: ... 1jkabcqlmndefJopghi

890@overload # `default` argument set 1DErstujkabcqlFGvwxymndefJHIzABCopghi

891def Field( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

892 default: _T, 1jkabcqlmndefJopghi

893 *, 

894 alias: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

895 alias_priority: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

896 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

897 serialization_alias: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

898 title: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

899 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

900 description: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

901 examples: list[Any] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

902 exclude: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

903 discriminator: str | types.Discriminator | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

904 deprecated: Deprecated | str | bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

905 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

906 frozen: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

907 validate_default: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

908 repr: bool = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

909 init: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

910 init_var: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

911 kw_only: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

912 pattern: str | typing.Pattern[str] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

913 strict: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

914 coerce_numbers_to_str: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

915 gt: annotated_types.SupportsGt | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

916 ge: annotated_types.SupportsGe | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

917 lt: annotated_types.SupportsLt | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

918 le: annotated_types.SupportsLe | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

919 multiple_of: float | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

920 allow_inf_nan: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

921 max_digits: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

922 decimal_places: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

923 min_length: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

924 max_length: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

925 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

926 fail_fast: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

927 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefJopghi

928) -> _T: ... 1jkabcqlmndefJopghi

929@overload # `default_factory` argument set 1DErstujkabcqlFGvwxymndefJHIzABCopghi

930def Field( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

931 *, 

932 default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T], 1jkabcqlmndefJopghi

933 alias: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

934 alias_priority: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

935 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

936 serialization_alias: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

937 title: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

938 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

939 description: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

940 examples: list[Any] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

941 exclude: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

942 discriminator: str | types.Discriminator | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

943 deprecated: Deprecated | str | bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

944 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

945 frozen: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

946 validate_default: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

947 repr: bool = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

948 init: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

949 init_var: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

950 kw_only: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

951 pattern: str | typing.Pattern[str] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

952 strict: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

953 coerce_numbers_to_str: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

954 gt: annotated_types.SupportsGt | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

955 ge: annotated_types.SupportsGe | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

956 lt: annotated_types.SupportsLt | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

957 le: annotated_types.SupportsLe | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

958 multiple_of: float | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

959 allow_inf_nan: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

960 max_digits: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

961 decimal_places: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

962 min_length: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

963 max_length: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

964 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

965 fail_fast: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

966 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefJopghi

967) -> _T: ... 1jkabcqlmndefJopghi

968@overload 1DErstujkabcqlFGvwxymndefJHIzABCopghi

969def Field( # No default set 1DErstujkabcqlFGvwxymndefJHIzABCopghi

970 *, 

971 alias: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

972 alias_priority: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

973 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

974 serialization_alias: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

975 title: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

976 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

977 description: str | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

978 examples: list[Any] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

979 exclude: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

980 discriminator: str | types.Discriminator | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

981 deprecated: Deprecated | str | bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

982 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

983 frozen: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

984 validate_default: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

985 repr: bool = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

986 init: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

987 init_var: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

988 kw_only: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

989 pattern: str | typing.Pattern[str] | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

990 strict: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

991 coerce_numbers_to_str: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

992 gt: annotated_types.SupportsGt | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

993 ge: annotated_types.SupportsGe | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

994 lt: annotated_types.SupportsLt | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

995 le: annotated_types.SupportsLe | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

996 multiple_of: float | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

997 allow_inf_nan: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

998 max_digits: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

999 decimal_places: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1000 min_length: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1001 max_length: int | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1002 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1003 fail_fast: bool | None = _Unset, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1004 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefJopghi

1005) -> Any: ... 1jkabcqlmndefJopghi

1006def Field( # noqa: C901 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1007 default: Any = PydanticUndefined, 

1008 *, 

1009 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = _Unset, 

1010 alias: str | None = _Unset, 

1011 alias_priority: int | None = _Unset, 

1012 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 

1013 serialization_alias: str | None = _Unset, 

1014 title: str | None = _Unset, 

1015 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 

1016 description: str | None = _Unset, 

1017 examples: list[Any] | None = _Unset, 

1018 exclude: bool | None = _Unset, 

1019 discriminator: str | types.Discriminator | None = _Unset, 

1020 deprecated: Deprecated | str | bool | None = _Unset, 

1021 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 

1022 frozen: bool | None = _Unset, 

1023 validate_default: bool | None = _Unset, 

1024 repr: bool = _Unset, 

1025 init: bool | None = _Unset, 

1026 init_var: bool | None = _Unset, 

1027 kw_only: bool | None = _Unset, 

1028 pattern: str | typing.Pattern[str] | None = _Unset, 

1029 strict: bool | None = _Unset, 

1030 coerce_numbers_to_str: bool | None = _Unset, 

1031 gt: annotated_types.SupportsGt | None = _Unset, 

1032 ge: annotated_types.SupportsGe | None = _Unset, 

1033 lt: annotated_types.SupportsLt | None = _Unset, 

1034 le: annotated_types.SupportsLe | None = _Unset, 

1035 multiple_of: float | None = _Unset, 

1036 allow_inf_nan: bool | None = _Unset, 

1037 max_digits: int | None = _Unset, 

1038 decimal_places: int | None = _Unset, 

1039 min_length: int | None = _Unset, 

1040 max_length: int | None = _Unset, 

1041 union_mode: Literal['smart', 'left_to_right'] = _Unset, 

1042 fail_fast: bool | None = _Unset, 

1043 **extra: Unpack[_EmptyKwargs], 

1044) -> Any: 

1045 """!!! abstract "Usage Documentation" 

1046 [Fields](../concepts/fields.md) 

1047 

1048 Create a field for objects that can be configured. 

1049 

1050 Used to provide extra information about a field, either for the model schema or complex validation. Some arguments 

1051 apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`. 

1052 

1053 Note: 

1054 - 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` 

1055 

1056 Args: 

1057 default: Default value if the field is not set. 

1058 default_factory: A callable to generate the default value. The callable can either take 0 arguments 

1059 (in which case it is called as is) or a single argument containing the already validated data. 

1060 alias: The name to use for the attribute when validating or serializing by alias. 

1061 This is often used for things like converting between snake and camel case. 

1062 alias_priority: Priority of the alias. This affects whether an alias generator is used. 

1063 validation_alias: Like `alias`, but only affects validation, not serialization. 

1064 serialization_alias: Like `alias`, but only affects serialization, not validation. 

1065 title: Human-readable title. 

1066 field_title_generator: A callable that takes a field name and returns title for it. 

1067 description: Human-readable description. 

1068 examples: Example values for this field. 

1069 exclude: Whether to exclude the field from the model serialization. 

1070 discriminator: Field name or Discriminator for discriminating the type in a tagged union. 

1071 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, 

1072 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. 

1073 json_schema_extra: A dict or callable to provide extra JSON schema properties. 

1074 frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error. 

1075 validate_default: If `True`, apply validation to the default value every time you create an instance. 

1076 Otherwise, for performance reasons, the default value of the field is trusted and not validated. 

1077 repr: A boolean indicating whether to include the field in the `__repr__` output. 

1078 init: Whether the field should be included in the constructor of the dataclass. 

1079 (Only applies to dataclasses.) 

1080 init_var: Whether the field should _only_ be included in the constructor of the dataclass. 

1081 (Only applies to dataclasses.) 

1082 kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass. 

1083 (Only applies to dataclasses.) 

1084 coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode). 

1085 strict: If `True`, strict validation is applied to the field. 

1086 See [Strict Mode](../concepts/strict_mode.md) for details. 

1087 gt: Greater than. If set, value must be greater than this. Only applicable to numbers. 

1088 ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. 

1089 lt: Less than. If set, value must be less than this. Only applicable to numbers. 

1090 le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. 

1091 multiple_of: Value must be a multiple of this. Only applicable to numbers. 

1092 min_length: Minimum length for iterables. 

1093 max_length: Maximum length for iterables. 

1094 pattern: Pattern for strings (a regular expression). 

1095 allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to float and [`Decimal`][decimal.Decimal] numbers. 

1096 max_digits: Maximum number of allow digits for strings. 

1097 decimal_places: Maximum number of decimal places allowed for numbers. 

1098 union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`. 

1099 See [Union Mode](../concepts/unions.md#union-modes) for details. 

1100 fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected. 

1101 This option can be applied only to iterable types (list, tuple, set, and frozenset). 

1102 extra: (Deprecated) Extra fields that will be included in the JSON schema. 

1103 

1104 !!! warning Deprecated 

1105 The `extra` kwargs is deprecated. Use `json_schema_extra` instead. 

1106 

1107 Returns: 

1108 A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on 

1109 type-annotated fields without causing a type error. 

1110 """ 

1111 # Check deprecated and removed params from V1. This logic should eventually be removed. 

1112 const = extra.pop('const', None) # type: ignore 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1113 if const is not None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1114 raise PydanticUserError('`const` is removed, use `Literal` instead', code='removed-kwargs') 1DErstujkabcqlFGvwxymndefHIzABCopghi

1115 

1116 min_items = extra.pop('min_items', None) # type: ignore 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1117 if min_items is not None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1118 warn('`min_items` is deprecated and will be removed, use `min_length` instead', DeprecationWarning) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1119 if min_length in (None, _Unset): 1DErstujkabcqlFGvwxymndefHIzABCopghi

1120 min_length = min_items # type: ignore 1DErstujkabcqlFGvwxymndefHIzABCopghi

1121 

1122 max_items = extra.pop('max_items', None) # type: ignore 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1123 if max_items is not None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1124 warn('`max_items` is deprecated and will be removed, use `max_length` instead', DeprecationWarning) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1125 if max_length in (None, _Unset): 1DErstujkabcqlFGvwxymndefHIzABCopghi

1126 max_length = max_items # type: ignore 1DErstujkabcqlFGvwxymndefHIzABCopghi

1127 

1128 unique_items = extra.pop('unique_items', None) # type: ignore 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1129 if unique_items is not None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1130 raise PydanticUserError( 1DErstujkabcqlFGvwxymndefHIzABCopghi

1131 ( 

1132 '`unique_items` is removed, use `Set` instead' 

1133 '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)' 

1134 ), 

1135 code='removed-kwargs', 

1136 ) 

1137 

1138 allow_mutation = extra.pop('allow_mutation', None) # type: ignore 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1139 if allow_mutation is not None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1140 warn('`allow_mutation` is deprecated and will be removed. use `frozen` instead', DeprecationWarning) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1141 if allow_mutation is False: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1142 frozen = True 1DErstujkabcqlFGvwxymndefHIzABCopghi

1143 

1144 regex = extra.pop('regex', None) # type: ignore 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1145 if regex is not None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1146 raise PydanticUserError('`regex` is removed. use `pattern` instead', code='removed-kwargs') 1DErstujkabcqlFGvwxymndefHIzABCopghi

1147 

1148 if extra: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1149 warn( 1DErstujkabcqlFGvwxymndefHIzABCopghi

1150 'Using extra keyword arguments on `Field` is deprecated and will be removed.' 

1151 ' Use `json_schema_extra` instead.' 

1152 f' (Extra keys: {", ".join(k.__repr__() for k in extra.keys())})', 

1153 DeprecationWarning, 

1154 ) 

1155 if not json_schema_extra or json_schema_extra is _Unset: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1156 json_schema_extra = extra # type: ignore 1DErstujkabcqlFGvwxymndefHIzABCopghi

1157 

1158 if ( 1DErstuqlFGvwxyHIzABC

1159 validation_alias 

1160 and validation_alias is not _Unset 

1161 and not isinstance(validation_alias, (str, AliasChoices, AliasPath)) 

1162 ): 

1163 raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`') 1DErstujkabcqlFGvwxymndefHIzABCopghi

1164 

1165 if serialization_alias in (_Unset, None) and isinstance(alias, str): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1166 serialization_alias = alias 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1167 

1168 if validation_alias in (_Unset, None): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1169 validation_alias = alias 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1170 

1171 include = extra.pop('include', None) # type: ignore 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1172 if include is not None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1173 warn('`include` is deprecated and does nothing. It will be removed, use `exclude` instead', DeprecationWarning) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1174 

1175 return FieldInfo.from_field( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1176 default, 

1177 default_factory=default_factory, 

1178 alias=alias, 

1179 alias_priority=alias_priority, 

1180 validation_alias=validation_alias, 

1181 serialization_alias=serialization_alias, 

1182 title=title, 

1183 field_title_generator=field_title_generator, 

1184 description=description, 

1185 examples=examples, 

1186 exclude=exclude, 

1187 discriminator=discriminator, 

1188 deprecated=deprecated, 

1189 json_schema_extra=json_schema_extra, 

1190 frozen=frozen, 

1191 pattern=pattern, 

1192 validate_default=validate_default, 

1193 repr=repr, 

1194 init=init, 

1195 init_var=init_var, 

1196 kw_only=kw_only, 

1197 coerce_numbers_to_str=coerce_numbers_to_str, 

1198 strict=strict, 

1199 gt=gt, 

1200 ge=ge, 

1201 lt=lt, 

1202 le=le, 

1203 multiple_of=multiple_of, 

1204 min_length=min_length, 

1205 max_length=max_length, 

1206 allow_inf_nan=allow_inf_nan, 

1207 max_digits=max_digits, 

1208 decimal_places=decimal_places, 

1209 union_mode=union_mode, 

1210 fail_fast=fail_fast, 

1211 ) 

1212 

1213 

1214_FIELD_ARG_NAMES = set(inspect.signature(Field).parameters) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1215_FIELD_ARG_NAMES.remove('extra') # do not include the varkwargs parameter 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1216 

1217 

1218class ModelPrivateAttr(_repr.Representation): 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1219 """A descriptor for private attributes in class models. 

1220 

1221 !!! warning 

1222 You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use 

1223 `pydantic.fields.PrivateAttr`. (This is similar to `FieldInfo` vs. `Field`.) 

1224 

1225 Attributes: 

1226 default: The default value of the attribute if not provided. 

1227 default_factory: A callable function that generates the default value of the 

1228 attribute if not provided. 

1229 """ 

1230 

1231 __slots__ = ('default', 'default_factory') 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1232 

1233 def __init__( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1234 self, default: Any = PydanticUndefined, *, default_factory: typing.Callable[[], Any] | None = None 

1235 ) -> None: 

1236 if default is Ellipsis: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1237 self.default = PydanticUndefined 1DErstujkabcqlFGvwxymndefHIzABCopghi

1238 else: 

1239 self.default = default 1DErstujkabcqlFGvwxymndefHIzABCopghi

1240 self.default_factory = default_factory 1DErstujkabcqlFGvwxymndefHIzABCopghi

1241 

1242 if not typing.TYPE_CHECKING: 1242 ↛ 1254line 1242 didn't jump to line 1254 because the condition on line 1242 was always true1DErstujkabcqlFGvwxymndefJHIzABCopghi

1243 # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access 

1244 

1245 def __getattr__(self, item: str) -> Any: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1246 """This function improves compatibility with custom descriptors by ensuring delegation happens 

1247 as expected when the default value of a private attribute is a descriptor. 

1248 """ 

1249 if item in {'__get__', '__set__', '__delete__'}: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1250 if hasattr(self.default, item): 1DErstujkabcqlFGvwxymndefHIzABCopghi

1251 return getattr(self.default, item) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1252 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') 1DErstujkabcqlFGvwxymndefHIzABCopghi

1253 

1254 def __set_name__(self, cls: type[Any], name: str) -> None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1255 """Preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487.""" 

1256 default = self.default 1DErstujkabcqlFGvwxymndefHIzABCopghi

1257 if default is PydanticUndefined: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1258 return 1DErstujkabcqlFGvwxymndefHIzABCopghi

1259 set_name = getattr(default, '__set_name__', None) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1260 if callable(set_name): 1DErstujkabcqlFGvwxymndefHIzABCopghi

1261 set_name(cls, name) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1262 

1263 def get_default(self) -> Any: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1264 """Retrieve the default value of the object. 

1265 

1266 If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object. 

1267 

1268 If `self.default_factory` is not `None`, it will call `self.default_factory` and return the value returned. 

1269 

1270 Returns: 

1271 The default value of the object. 

1272 """ 

1273 return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() 1DErstujkabcqlFGvwxymndefHIzABCopghi

1274 

1275 def __eq__(self, other: Any) -> bool: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1276 return isinstance(other, self.__class__) and (self.default, self.default_factory) == ( 1DErstujkabcqlFGvwxymndefHIzABCopghi

1277 other.default, 

1278 other.default_factory, 

1279 ) 

1280 

1281 

1282# NOTE: Actual return type is 'ModelPrivateAttr', but we want to help type checkers 

1283# to understand the magic that happens at runtime. 

1284@overload # `default` argument set 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1285def PrivateAttr( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1286 default: _T, 1jkabcqlmndefJopghi

1287 *, 

1288 init: Literal[False] = False, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1289) -> _T: ... 1jkabcqlmndefJopghi

1290@overload # `default_factory` argument set 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1291def PrivateAttr( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1292 *, 

1293 default_factory: Callable[[], _T], 1jkabcqlmndefJopghi

1294 init: Literal[False] = False, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1295) -> _T: ... 1jkabcqlmndefJopghi

1296@overload # No default set 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1297def PrivateAttr( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1298 *, 

1299 init: Literal[False] = False, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1300) -> Any: ... 1jkabcqlmndefJopghi

1301def PrivateAttr( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1302 default: Any = PydanticUndefined, 

1303 *, 

1304 default_factory: Callable[[], Any] | None = None, 

1305 init: Literal[False] = False, 

1306) -> Any: 

1307 """!!! abstract "Usage Documentation" 

1308 [Private Model Attributes](../concepts/models.md#private-model-attributes) 

1309 

1310 Indicates that an attribute is intended for private use and not handled during normal validation/serialization. 

1311 

1312 Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner. 

1313 

1314 Private attributes are stored in `__private_attributes__` on the model. 

1315 

1316 Args: 

1317 default: The attribute's default value. Defaults to Undefined. 

1318 default_factory: Callable that will be 

1319 called when a default value is needed for this attribute. 

1320 If both `default` and `default_factory` are set, an error will be raised. 

1321 init: Whether the attribute should be included in the constructor of the dataclass. Always `False`. 

1322 

1323 Returns: 

1324 An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class. 

1325 

1326 Raises: 

1327 ValueError: If both `default` and `default_factory` are set. 

1328 """ 

1329 if default is not PydanticUndefined and default_factory is not None: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1330 raise TypeError('cannot specify both default and default_factory') 1DErstujkabcqlFGvwxymndefHIzABCopghi

1331 

1332 return ModelPrivateAttr( 1DErstujkabcqlFGvwxymndefHIzABCopghi

1333 default, 

1334 default_factory=default_factory, 

1335 ) 

1336 

1337 

1338@dataclasses.dataclass(**_internal_dataclass.slots_true) 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1339class ComputedFieldInfo: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1340 """A container for data from `@computed_field` so that we can access it while building the pydantic-core schema. 

1341 

1342 Attributes: 

1343 decorator_repr: A class variable representing the decorator string, '@computed_field'. 

1344 wrapped_property: The wrapped computed field property. 

1345 return_type: The type of the computed field property's return value. 

1346 alias: The alias of the property to be used during serialization. 

1347 alias_priority: The priority of the alias. This affects whether an alias generator is used. 

1348 title: Title of the computed field to include in the serialization JSON schema. 

1349 field_title_generator: A callable that takes a field name and returns title for it. 

1350 description: Description of the computed field to include in the serialization JSON schema. 

1351 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, 

1352 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. 

1353 examples: Example values of the computed field to include in the serialization JSON schema. 

1354 json_schema_extra: A dict or callable to provide extra JSON schema properties. 

1355 repr: A boolean indicating whether to include the field in the __repr__ output. 

1356 """ 

1357 

1358 decorator_repr: ClassVar[str] = '@computed_field' 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1359 wrapped_property: property 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1360 return_type: Any 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1361 alias: str | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1362 alias_priority: int | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1363 title: str | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1364 field_title_generator: Callable[[str, ComputedFieldInfo], str] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1365 description: str | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1366 deprecated: Deprecated | str | bool | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1367 examples: list[Any] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1368 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1369 repr: bool 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1370 

1371 @property 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1372 def deprecation_message(self) -> str | None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1373 """The deprecation message to be emitted, or `None` if not set.""" 

1374 if self.deprecated is None: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1375 return None 1DErstujkabcqlFGvwxymndefHIzABCopghi

1376 if isinstance(self.deprecated, bool): 1DErstujkabcqlFGvwxymndefHIzABCopghi

1377 return 'deprecated' if self.deprecated else None 1DErstujkabcqlFGvwxymndefHIzABCopghi

1378 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1DErstujkabcqlFGvwxymndefHIzABCopghi

1379 

1380 def _update_from_config(self, config_wrapper: ConfigWrapper, name: str) -> None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1381 """Update the instance from the configuration set on the class this computed field belongs to.""" 

1382 title_generator = self.field_title_generator or config_wrapper.field_title_generator 1DErstujkabcqlFGvwxymndefHIzABCopghi

1383 if title_generator is not None and self.title is None: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1384 self.title = title_generator(name, self) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1385 if config_wrapper.alias_generator is not None: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1386 self._apply_alias_generator(config_wrapper.alias_generator, name) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1387 

1388 def _apply_alias_generator(self, alias_generator: Callable[[str], str] | AliasGenerator, name: str) -> None: 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1389 """Apply an alias generator to aliases if appropriate. 

1390 

1391 Args: 

1392 alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance. 

1393 name: The name of the computed field from which to generate the alias. 

1394 """ 

1395 # Apply an alias_generator if 

1396 # 1. An alias is not specified 

1397 # 2. An alias is specified, but the priority is <= 1 

1398 

1399 if self.alias_priority is None or self.alias_priority <= 1 or self.alias is None: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1400 alias, _, serialization_alias = None, None, None 1DErstujkabcqlFGvwxymndefHIzABCopghi

1401 

1402 if isinstance(alias_generator, AliasGenerator): 1DErstujkabcqlFGvwxymndefHIzABCopghi

1403 alias, _, serialization_alias = alias_generator.generate_aliases(name) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1404 elif callable(alias_generator): 1404 ↛ 1410line 1404 didn't jump to line 1410 because the condition on line 1404 was always true1DErstujkabcqlFGvwxymndefHIzABCopghi

1405 alias = alias_generator(name) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1406 

1407 # if priority is not set, we set to 1 

1408 # which supports the case where the alias_generator from a child class is used 

1409 # to generate an alias for a field in a parent class 

1410 if self.alias_priority is None or self.alias_priority <= 1: 1410 ↛ 1416line 1410 didn't jump to line 1416 because the condition on line 1410 was always true1DErstujkabcqlFGvwxymndefHIzABCopghi

1411 self.alias_priority = 1 1DErstujkabcqlFGvwxymndefHIzABCopghi

1412 

1413 # if the priority is 1, then we set the aliases to the generated alias 

1414 # note that we use the serialization_alias with priority over alias, as computed_field 

1415 # aliases are used for serialization only (not validation) 

1416 if self.alias_priority == 1: 1416 ↛ exitline 1416 didn't return from function '_apply_alias_generator' because the condition on line 1416 was always true1DErstujkabcqlFGvwxymndefHIzABCopghi

1417 self.alias = _utils.get_first_not_none(serialization_alias, alias) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1418 

1419 

1420def _wrapped_property_is_private(property_: cached_property | property) -> bool: # type: ignore 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1421 """Returns true if provided property is private, False otherwise.""" 

1422 wrapped_name: str = '' 1DErstujkabcqlFGvwxymndefHIzABCopghi

1423 

1424 if isinstance(property_, property): 1DErstujkabcqlFGvwxymndefHIzABCopghi

1425 wrapped_name = getattr(property_.fget, '__name__', '') 1DErstujkabcqlFGvwxymndefHIzABCopghi

1426 elif isinstance(property_, cached_property): # type: ignore 1DErstujkabcqlFGvwxymndefHIzABCopghi

1427 wrapped_name = getattr(property_.func, '__name__', '') # type: ignore 1DErstujkabcqlFGvwxymndefHIzABCopghi

1428 

1429 return wrapped_name.startswith('_') and not wrapped_name.startswith('__') 1DErstujkabcqlFGvwxymndefHIzABCopghi

1430 

1431 

1432# this should really be `property[T], cached_property[T]` but property is not generic unlike cached_property 

1433# See https://github.com/python/typing/issues/985 and linked issues 

1434PropertyT = typing.TypeVar('PropertyT') 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1435 

1436 

1437@typing.overload 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1438def computed_field(func: PropertyT, /) -> PropertyT: ... 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1439 

1440 

1441@typing.overload 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1442def computed_field( 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1443 *, 

1444 alias: str | None = None, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1445 alias_priority: int | None = None, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1446 title: str | None = None, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1447 field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1448 description: str | None = None, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1449 deprecated: Deprecated | str | bool | None = None, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1450 examples: list[Any] | None = None, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1451 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1452 repr: bool = True, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1453 return_type: Any = PydanticUndefined, 1DErstujkabcqlFGvwxymndefJHIzABCopghi

1454) -> typing.Callable[[PropertyT], PropertyT]: ... 1jkabcqlmndefJopghi

1455 

1456 

1457def computed_field( 1DErstujkabcFGvwxymndefJHIzABCopghi

1458 func: PropertyT | None = None, 

1459 /, 

1460 *, 

1461 alias: str | None = None, 

1462 alias_priority: int | None = None, 

1463 title: str | None = None, 

1464 field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None, 

1465 description: str | None = None, 

1466 deprecated: Deprecated | str | bool | None = None, 

1467 examples: list[Any] | None = None, 

1468 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None, 

1469 repr: bool | None = None, 

1470 return_type: Any = PydanticUndefined, 

1471) -> PropertyT | typing.Callable[[PropertyT], PropertyT]: 

1472 """!!! abstract "Usage Documentation" 

1473 [The `computed_field` decorator](../concepts/fields.md#the-computed_field-decorator) 

1474 

1475 Decorator to include `property` and `cached_property` when serializing models or dataclasses. 

1476 

1477 This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached. 

1478 

1479 ```python 

1480 from pydantic import BaseModel, computed_field 

1481 

1482 class Rectangle(BaseModel): 

1483 width: int 

1484 length: int 

1485 

1486 @computed_field 

1487 @property 

1488 def area(self) -> int: 

1489 return self.width * self.length 

1490 

1491 print(Rectangle(width=3, length=2).model_dump()) 

1492 #> {'width': 3, 'length': 2, 'area': 6} 

1493 ``` 

1494 

1495 If applied to functions not yet decorated with `@property` or `@cached_property`, the function is 

1496 automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE, 

1497 and confuse static type checkers, thus explicit use of `@property` is recommended. 

1498 

1499 !!! warning "Mypy Warning" 

1500 Even with the `@property` or `@cached_property` applied to your function before `@computed_field`, 

1501 mypy may throw a `Decorated property not supported` error. 

1502 See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information. 

1503 To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line. 

1504 

1505 [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error. 

1506 

1507 ```python 

1508 import random 

1509 

1510 from pydantic import BaseModel, computed_field 

1511 

1512 class Square(BaseModel): 

1513 width: float 

1514 

1515 @computed_field 

1516 def area(self) -> float: # converted to a `property` by `computed_field` 

1517 return round(self.width**2, 2) 

1518 

1519 @area.setter 

1520 def area(self, new_area: float) -> None: 

1521 self.width = new_area**0.5 

1522 

1523 @computed_field(alias='the magic number', repr=False) 

1524 def random_number(self) -> int: 

1525 return random.randint(0, 1_000) 

1526 

1527 square = Square(width=1.3) 

1528 

1529 # `random_number` does not appear in representation 

1530 print(repr(square)) 

1531 #> Square(width=1.3, area=1.69) 

1532 

1533 print(square.random_number) 

1534 #> 3 

1535 

1536 square.area = 4 

1537 

1538 print(square.model_dump_json(by_alias=True)) 

1539 #> {"width":2.0,"area":4.0,"the magic number":3} 

1540 ``` 

1541 

1542 !!! warning "Overriding with `computed_field`" 

1543 You can't override a field from a parent class with a `computed_field` in the child class. 

1544 `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either. 

1545 See the example below: 

1546 

1547 ```python 

1548 from pydantic import BaseModel, computed_field 

1549 

1550 class Parent(BaseModel): 

1551 a: str 

1552 

1553 try: 

1554 

1555 class Child(Parent): 

1556 @computed_field 

1557 @property 

1558 def a(self) -> str: 

1559 return 'new a' 

1560 

1561 except TypeError as e: 

1562 print(e) 

1563 ''' 

1564 Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible. 

1565 ''' 

1566 ``` 

1567 

1568 Private properties decorated with `@computed_field` have `repr=False` by default. 

1569 

1570 ```python 

1571 from functools import cached_property 

1572 

1573 from pydantic import BaseModel, computed_field 

1574 

1575 class Model(BaseModel): 

1576 foo: int 

1577 

1578 @computed_field 

1579 @cached_property 

1580 def _private_cached_property(self) -> int: 

1581 return -self.foo 

1582 

1583 @computed_field 

1584 @property 

1585 def _private_property(self) -> int: 

1586 return -self.foo 

1587 

1588 m = Model(foo=1) 

1589 print(repr(m)) 

1590 #> Model(foo=1) 

1591 ``` 

1592 

1593 Args: 

1594 func: the function to wrap. 

1595 alias: alias to use when serializing this computed field, only used when `by_alias=True` 

1596 alias_priority: priority of the alias. This affects whether an alias generator is used 

1597 title: Title to use when including this computed field in JSON Schema 

1598 field_title_generator: A callable that takes a field name and returns title for it. 

1599 description: Description to use when including this computed field in JSON Schema, defaults to the function's 

1600 docstring 

1601 deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport). 

1602 to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the 

1603 `deprecated` decorator. 

1604 examples: Example values to use when including this computed field in JSON Schema 

1605 json_schema_extra: A dict or callable to provide extra JSON schema properties. 

1606 repr: whether to include this computed field in model repr. 

1607 Default is `False` for private properties and `True` for public properties. 

1608 return_type: optional return for serialization logic to expect when serializing to JSON, if included 

1609 this must be correct, otherwise a `TypeError` is raised. 

1610 If you don't include a return type Any is used, which does runtime introspection to handle arbitrary 

1611 objects. 

1612 

1613 Returns: 

1614 A proxy wrapper for the property. 

1615 """ 

1616 

1617 def dec(f: Any) -> Any: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1618 nonlocal description, deprecated, return_type, alias_priority 

1619 unwrapped = _decorators.unwrap_wrapped_function(f) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1620 

1621 if description is None and unwrapped.__doc__: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1622 description = inspect.cleandoc(unwrapped.__doc__) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1623 

1624 if deprecated is None and hasattr(unwrapped, '__deprecated__'): 1DErstujkabcqlFGvwxymndefHIzABCopghi

1625 deprecated = unwrapped.__deprecated__ 1DErstujkabcqlFGvwxymndefHIzABCopghi

1626 

1627 # if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now 

1628 f = _decorators.ensure_property(f) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1629 alias_priority = (alias_priority or 2) if alias is not None else None 1DErstujkabcqlFGvwxymndefHIzABCopghi

1630 

1631 if repr is None: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1632 repr_: bool = not _wrapped_property_is_private(property_=f) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1633 else: 

1634 repr_ = repr 1DErstujkabcqlFGvwxymndefHIzABCopghi

1635 

1636 dec_info = ComputedFieldInfo( 1DErstujkabcqlFGvwxymndefHIzABCopghi

1637 f, 

1638 return_type, 

1639 alias, 

1640 alias_priority, 

1641 title, 

1642 field_title_generator, 

1643 description, 

1644 deprecated, 

1645 examples, 

1646 json_schema_extra, 

1647 repr_, 

1648 ) 

1649 return _decorators.PydanticDescriptorProxy(f, dec_info) 1DErstujkabcqlFGvwxymndefHIzABCopghi

1650 

1651 if func is None: 1DErstujkabcqlFGvwxymndefHIzABCopghi

1652 return dec 1DErstujkabcqlFGvwxymndefHIzABCopghi

1653 else: 

1654 return dec(func) 1DErstujkabcqlFGvwxymndefHIzABCopghi