Coverage for pydantic/fields.py: 99.19%

420 statements  

« prev     ^ index     » next       coverage.py v7.5.3, created at 2024-06-21 17:00 +0000

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

2 

3from __future__ import annotations as _annotations 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

4 

5import dataclasses 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

6import inspect 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

7import sys 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

8import typing 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

9from copy import copy 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

10from dataclasses import Field as DataclassField 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

11from functools import cached_property 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

12from typing import Any, ClassVar 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

13from warnings import warn 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

14 

15import annotated_types 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

16import typing_extensions 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

17from pydantic_core import PydanticUndefined 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

18from typing_extensions import Literal, TypeAlias, Unpack, deprecated 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

19 

20from . import types 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

21from ._internal import _decorators, _fields, _generics, _internal_dataclass, _repr, _typing_extra, _utils 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

22from .aliases import AliasChoices, AliasPath 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

23from .config import JsonDict 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

24from .errors import PydanticUserError 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

25from .warnings import PydanticDeprecatedSince20 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

26 

27if typing.TYPE_CHECKING: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

28 from ._internal._repr import ReprArgs 1a

29else: 

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

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

32 DeprecationWarning = PydanticDeprecatedSince20 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

33 

34__all__ = 'Field', 'PrivateAttr', 'computed_field' 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

35 

36 

37_Unset: Any = PydanticUndefined 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

38 

39if sys.version_info >= (3, 13): 39 ↛ 40line 39 didn't jump to line 40, because the condition on line 39 was never true1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

40 import warnings 

41 

42 Deprecated: TypeAlias = warnings.deprecated | deprecated 

43else: 

44 Deprecated: TypeAlias = deprecated 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

45 

46 

47class _FromFieldInfoInputs(typing_extensions.TypedDict, total=False): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

49 

50 annotation: type[Any] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

51 default_factory: typing.Callable[[], Any] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

52 alias: str | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

53 alias_priority: int | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

54 validation_alias: str | AliasPath | AliasChoices | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

55 serialization_alias: str | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

56 title: str | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

57 description: str | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

58 examples: list[Any] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

59 exclude: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

60 gt: annotated_types.SupportsGt | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

61 ge: annotated_types.SupportsGe | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

62 lt: annotated_types.SupportsLt | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

63 le: annotated_types.SupportsLe | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

64 multiple_of: float | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

65 strict: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

66 min_length: int | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

67 max_length: int | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

68 pattern: str | typing.Pattern[str] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

69 allow_inf_nan: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

70 max_digits: int | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

71 decimal_places: int | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

72 union_mode: Literal['smart', 'left_to_right'] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

73 discriminator: str | types.Discriminator | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

74 deprecated: Deprecated | str | bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

75 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

76 frozen: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

77 validate_default: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

78 repr: bool 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

79 init: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

80 init_var: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

81 kw_only: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

82 coerce_numbers_to_str: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

83 

84 

85class _FieldInfoInputs(_FromFieldInfoInputs, total=False): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

87 

88 default: Any 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

89 

90 

91class FieldInfo(_repr.Representation): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

93 

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

95 function is explicitly used. 

96 

97 !!! warning 

98 You generally shouldn't be creating `FieldInfo` directly, you'll only need to use it when accessing 

99 [`BaseModel`][pydantic.main.BaseModel] `.model_fields` internals. 

100 

101 Attributes: 

102 annotation: The type annotation of the field. 

103 default: The default value of the field. 

104 default_factory: The factory function used to construct the default for the field. 

105 alias: The alias name of the field. 

106 alias_priority: The priority of the field's alias. 

107 validation_alias: The validation alias of the field. 

108 serialization_alias: The serialization alias of the field. 

109 title: The title of the field. 

110 description: The description of the field. 

111 examples: List of examples of the field. 

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

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

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

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

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

117 frozen: Whether the field is frozen. 

118 validate_default: Whether to validate the default value of the field. 

119 repr: Whether to include the field in representation of the model. 

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

121 init_var: Whether the field should _only_ be included in the constructor of the dataclass, and not stored. 

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

123 metadata: List of metadata constraints. 

124 """ 

125 

126 annotation: type[Any] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

127 default: Any 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

128 default_factory: typing.Callable[[], Any] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

129 alias: str | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

130 alias_priority: int | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

131 validation_alias: str | AliasPath | AliasChoices | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

132 serialization_alias: str | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

133 title: str | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

134 description: str | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

135 examples: list[Any] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

136 exclude: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

137 discriminator: str | types.Discriminator | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

138 deprecated: Deprecated | str | bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

139 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

140 frozen: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

141 validate_default: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

142 repr: bool 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

143 init: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

144 init_var: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

145 kw_only: bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

146 metadata: list[Any] 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

147 

148 __slots__ = ( 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

149 'annotation', 

150 'default', 

151 'default_factory', 

152 'alias', 

153 'alias_priority', 

154 'validation_alias', 

155 'serialization_alias', 

156 'title', 

157 'description', 

158 'examples', 

159 'exclude', 

160 'discriminator', 

161 'deprecated', 

162 'json_schema_extra', 

163 'frozen', 

164 'validate_default', 

165 'repr', 

166 'init', 

167 'init_var', 

168 'kw_only', 

169 'metadata', 

170 '_attributes_set', 

171 ) 

172 

173 # used to convert kwargs to metadata/constraints, 

174 # None has a special meaning - these items are collected into a `PydanticGeneralMetadata` 

175 metadata_lookup: ClassVar[dict[str, typing.Callable[[Any], Any] | None]] = { 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

176 'strict': types.Strict, 

177 'gt': annotated_types.Gt, 

178 'ge': annotated_types.Ge, 

179 'lt': annotated_types.Lt, 

180 'le': annotated_types.Le, 

181 'multiple_of': annotated_types.MultipleOf, 

182 'min_length': annotated_types.MinLen, 

183 'max_length': annotated_types.MaxLen, 

184 'pattern': None, 

185 'allow_inf_nan': None, 

186 'max_digits': None, 

187 'decimal_places': None, 

188 'union_mode': None, 

189 'coerce_numbers_to_str': None, 

190 } 

191 

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

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

194 or one of the constructor classmethods. 

195 

196 See the signature of `pydantic.fields.Field` for more details about the expected arguments. 

197 """ 

198 self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset} 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

200 self.annotation, annotation_metadata = self._extract_metadata(kwargs.get('annotation')) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

201 

202 default = kwargs.pop('default', PydanticUndefined) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

203 if default is Ellipsis: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

204 self.default = PydanticUndefined 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

205 else: 

206 self.default = default 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

207 

208 self.default_factory = kwargs.pop('default_factory', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

209 

210 if self.default is not PydanticUndefined and self.default_factory is not None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

211 raise TypeError('cannot specify both default and default_factory') 1bcdefghijklamnopqrstuvwxyzABCDEF

212 

213 self.title = kwargs.pop('title', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

214 self.alias = kwargs.pop('alias', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

215 self.validation_alias = kwargs.pop('validation_alias', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

216 self.serialization_alias = kwargs.pop('serialization_alias', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

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

219 self.description = kwargs.pop('description', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

220 self.examples = kwargs.pop('examples', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

221 self.exclude = kwargs.pop('exclude', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

222 self.discriminator = kwargs.pop('discriminator', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

223 # For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden 

224 self.deprecated = kwargs.pop('deprecated', getattr(self, 'deprecated', None)) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

225 self.repr = kwargs.pop('repr', True) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

226 self.json_schema_extra = kwargs.pop('json_schema_extra', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

227 self.validate_default = kwargs.pop('validate_default', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

228 self.frozen = kwargs.pop('frozen', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

229 # currently only used on dataclasses 

230 self.init = kwargs.pop('init', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

231 self.init_var = kwargs.pop('init_var', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

232 self.kw_only = kwargs.pop('kw_only', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

233 

234 self.metadata = self._collect_metadata(kwargs) + annotation_metadata # type: ignore 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

235 

236 @staticmethod 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

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

239 

240 Args: 

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

242 **kwargs: Additional arguments dictionary. 

243 

244 Raises: 

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

246 

247 Returns: 

248 A new FieldInfo object with the given parameters. 

249 

250 Example: 

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

252 

253 ```python 

254 import pydantic 

255 

256 class MyModel(pydantic.BaseModel): 

257 foo: int = pydantic.Field(4) 

258 ``` 

259 """ 

260 if 'annotation' in kwargs: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

262 return FieldInfo(default=default, **kwargs) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

263 

264 @staticmethod 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

265 def from_annotation(annotation: type[Any]) -> FieldInfo: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

267 

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

269 

270 ```python 

271 import pydantic 

272 

273 class MyModel(pydantic.BaseModel): 

274 foo: int # <-- like this 

275 ``` 

276 

277 We also account for the case where the annotation can be an instance of `Annotated` and where 

278 one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.: 

279 

280 ```python 

281 import annotated_types 

282 from typing_extensions import Annotated 

283 

284 import pydantic 

285 

286 class MyModel(pydantic.BaseModel): 

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

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

289 ``` 

290 

291 Args: 

292 annotation: An annotation object. 

293 

294 Returns: 

295 An instance of the field metadata. 

296 """ 

297 final = False 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

298 if _typing_extra.is_finalvar(annotation): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

299 final = True 1bcdefghijklamnopqrstuvwxyzABCDEF

300 if annotation is not typing_extensions.Final: 1bcdefghijklamnopqrstuvwxyzABCDEF

301 annotation = typing_extensions.get_args(annotation)[0] 1bcdefghijklamnopqrstuvwxyzABCDEF

302 

303 if _typing_extra.is_annotated(annotation): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

304 first_arg, *extra_args = typing_extensions.get_args(annotation) 1bcdefghijklamnopqrstuvwxyzABCDEF

305 if _typing_extra.is_finalvar(first_arg): 1bcdefghijklamnopqrstuvwxyzABCDEF

306 final = True 1bcdefghijklamnopqrstuvwxyzABCDEF

307 field_info_annotations = [a for a in extra_args if isinstance(a, FieldInfo)] 1bcdefghijklamnopqrstuvwxyzABCDEF

308 field_info = FieldInfo.merge_field_infos(*field_info_annotations, annotation=first_arg) 1bcdefghijklamnopqrstuvwxyzABCDEF

309 if field_info: 309 ↛ 324line 309 didn't jump to line 324, because the condition on line 309 was always true1bcdefghijklamnopqrstuvwxyzABCDEF

310 new_field_info = copy(field_info) 1bcdefghijklamnopqrstuvwxyzABCDEF

311 new_field_info.annotation = first_arg 1bcdefghijklamnopqrstuvwxyzABCDEF

312 new_field_info.frozen = final or field_info.frozen 1bcdefghijklamnopqrstuvwxyzABCDEF

313 metadata: list[Any] = [] 1bcdefghijklamnopqrstuvwxyzABCDEF

314 for a in extra_args: 1bcdefghijklamnopqrstuvwxyzABCDEF

315 if _typing_extra.is_deprecated_instance(a): 1bcdefghijklamnopqrstuvwxyzABCDEF

316 new_field_info.deprecated = a.message 1bcdefghijklamnopqrstuvwxyzABCDEF

317 elif not isinstance(a, FieldInfo): 1bcdefghijklamnopqrstuvwxyzABCDEF

318 metadata.append(a) 1bcdefghijklamnopqrstuvwxyzABCDEF

319 else: 

320 metadata.extend(a.metadata) 1bcdefghijklamnopqrstuvwxyzABCDEF

321 new_field_info.metadata = metadata 1bcdefghijklamnopqrstuvwxyzABCDEF

322 return new_field_info 1bcdefghijklamnopqrstuvwxyzABCDEF

323 

324 return FieldInfo(annotation=annotation, frozen=final or None) # pyright: ignore[reportArgumentType] 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

325 

326 @staticmethod 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

327 def from_annotated_attribute(annotation: type[Any], default: Any) -> FieldInfo: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

329 

330 This is used in cases like the following: 

331 

332 ```python 

333 import annotated_types 

334 from typing_extensions import Annotated 

335 

336 import pydantic 

337 

338 class MyModel(pydantic.BaseModel): 

339 foo: int = 4 # <-- like this 

340 bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this 

341 spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this 

342 ``` 

343 

344 Args: 

345 annotation: The type annotation of the field. 

346 default: The default value of the field. 

347 

348 Returns: 

349 A field object with the passed values. 

350 """ 

351 if annotation is default: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

352 raise PydanticUserError( 1bcdefghijklamnopqrstuvwxyzABCDEF

353 'Error when building FieldInfo from annotated attribute. ' 

354 "Make sure you don't have any field name clashing with a type annotation ", 

355 code='unevaluable-type-annotation', 

356 ) 

357 

358 final = False 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

359 if _typing_extra.is_finalvar(annotation): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

360 final = True 1bcdefghijklamnopqrstuvwxyzABCDEF

361 if annotation is not typing_extensions.Final: 1bcdefghijklamnopqrstuvwxyzABCDEF

362 annotation = typing_extensions.get_args(annotation)[0] 1bcdefghijklamnopqrstuvwxyzABCDEF

363 

364 if isinstance(default, FieldInfo): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

365 default.annotation, annotation_metadata = FieldInfo._extract_metadata(annotation) # pyright: ignore[reportArgumentType] 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

366 default.metadata += annotation_metadata 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

367 default = default.merge_field_infos( 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

368 *[x for x in annotation_metadata if isinstance(x, FieldInfo)], default, annotation=default.annotation 

369 ) 

370 default.frozen = final or default.frozen 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

371 return default 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

372 elif isinstance(default, dataclasses.Field): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

373 init_var = False 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

374 if annotation is dataclasses.InitVar: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

375 init_var = True 1bcdefghijklamnopqrstuvwxyzABCDEF

376 annotation = typing.cast(Any, Any) 1bcdefghijklamnopqrstuvwxyzABCDEF

377 elif isinstance(annotation, dataclasses.InitVar): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

378 init_var = True 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

379 annotation = annotation.type 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

380 pydantic_field = FieldInfo._from_dataclass_field(default) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

381 pydantic_field.annotation, annotation_metadata = FieldInfo._extract_metadata(annotation) # pyright: ignore[reportArgumentType] 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

382 pydantic_field.metadata += annotation_metadata 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

383 pydantic_field = pydantic_field.merge_field_infos( 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

384 *[x for x in annotation_metadata if isinstance(x, FieldInfo)], 

385 pydantic_field, 

386 annotation=pydantic_field.annotation, 

387 ) 

388 pydantic_field.frozen = final or pydantic_field.frozen 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

389 pydantic_field.init_var = init_var 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

390 pydantic_field.init = getattr(default, 'init', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

391 pydantic_field.kw_only = getattr(default, 'kw_only', None) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

392 return pydantic_field 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

393 else: 

394 if _typing_extra.is_annotated(annotation): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

395 first_arg, *extra_args = typing_extensions.get_args(annotation) 1bcdefghijklamnopqrstuvwxyzABCDEF

396 field_infos = [a for a in extra_args if isinstance(a, FieldInfo)] 1bcdefghijklamnopqrstuvwxyzABCDEF

397 field_info = FieldInfo.merge_field_infos(*field_infos, annotation=first_arg, default=default) 1bcdefghijklamnopqrstuvwxyzABCDEF

398 metadata: list[Any] = [] 1bcdefghijklamnopqrstuvwxyzABCDEF

399 for a in extra_args: 1bcdefghijklamnopqrstuvwxyzABCDEF

400 if _typing_extra.is_deprecated_instance(a): 1bcdefghijklamnopqrstuvwxyzABCDEF

401 field_info.deprecated = a.message 1bcdefghijklamnopqrstuvwxyzABCDEF

402 elif not isinstance(a, FieldInfo): 1bcdefghijklamnopqrstuvwxyzABCDEF

403 metadata.append(a) 1bcdefghijklamnopqrstuvwxyzABCDEF

404 else: 

405 metadata.extend(a.metadata) 1bcdefghijklamnopqrstuvwxyzABCDEF

406 field_info.metadata = metadata 1bcdefghijklamnopqrstuvwxyzABCDEF

407 return field_info 1bcdefghijklamnopqrstuvwxyzABCDEF

408 

409 return FieldInfo(annotation=annotation, default=default, frozen=final or None) # pyright: ignore[reportArgumentType] 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

410 

411 @staticmethod 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

412 def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

414 

415 Later `FieldInfo` instances override earlier ones. 

416 

417 Returns: 

418 FieldInfo: A merged FieldInfo instance. 

419 """ 

420 flattened_field_infos: list[FieldInfo] = [] 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

421 for field_info in field_infos: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

422 flattened_field_infos.extend(x for x in field_info.metadata if isinstance(x, FieldInfo)) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

423 flattened_field_infos.append(field_info) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

424 field_infos = tuple(flattened_field_infos) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

425 if len(field_infos) == 1: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

427 field_info = copy(field_infos[0]) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

428 field_info._attributes_set.update(overrides) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

429 

430 default_override = overrides.pop('default', PydanticUndefined) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

431 if default_override is Ellipsis: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

432 default_override = PydanticUndefined 1bcdefghijklamnopqrstuvwxyzABCDEF

433 if default_override is not PydanticUndefined: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

434 field_info.default = default_override 1bcdefghijklamnopqrstuvwxyzABCDEF

435 

436 for k, v in overrides.items(): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

437 setattr(field_info, k, v) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

438 return field_info # type: ignore 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

439 

440 new_kwargs: dict[str, Any] = {} 1bcdefghijklamnopqrstuvwxyzABCDEF

441 metadata = {} 1bcdefghijklamnopqrstuvwxyzABCDEF

442 for field_info in field_infos: 1bcdefghijklamnopqrstuvwxyzABCDEF

443 new_kwargs.update(field_info._attributes_set) 1bcdefghijklamnopqrstuvwxyzABCDEF

444 for x in field_info.metadata: 1bcdefghijklamnopqrstuvwxyzABCDEF

445 if not isinstance(x, FieldInfo): 1bcdefghijklamnopqrstuvwxyzABCDEF

446 metadata[type(x)] = x 1bcdefghijklamnopqrstuvwxyzABCDEF

447 new_kwargs.update(overrides) 1bcdefghijklamnopqrstuvwxyzABCDEF

448 field_info = FieldInfo(**new_kwargs) 1bcdefghijklamnopqrstuvwxyzABCDEF

449 field_info.metadata = list(metadata.values()) 1bcdefghijklamnopqrstuvwxyzABCDEF

450 return field_info 1bcdefghijklamnopqrstuvwxyzABCDEF

451 

452 @staticmethod 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

453 def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

455 

456 Args: 

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

458 

459 Returns: 

460 The corresponding `FieldInfo` instance. 

461 

462 Raises: 

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

464 """ 

465 default = dc_field.default 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

466 if default is dataclasses.MISSING: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

467 default = PydanticUndefined 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

468 

469 if dc_field.default_factory is dataclasses.MISSING: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

470 default_factory: typing.Callable[[], Any] | None = None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

471 else: 

472 default_factory = dc_field.default_factory 1bcdefghijklamnopqrstuvwxyzABCDEF

473 

474 # use the `Field` function so in correct kwargs raise the correct `TypeError` 

475 dc_field_metadata = {k: v for k, v in dc_field.metadata.items() if k in _FIELD_ARG_NAMES} 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

476 return Field(default=default, default_factory=default_factory, repr=dc_field.repr, **dc_field_metadata) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

477 

478 @staticmethod 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

479 def _extract_metadata(annotation: type[Any] | None) -> tuple[type[Any] | None, list[Any]]: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

480 """Tries to extract metadata/constraints from an annotation if it uses `Annotated`. 

481 

482 Args: 

483 annotation: The type hint annotation for which metadata has to be extracted. 

484 

485 Returns: 

486 A tuple containing the extracted metadata type and the list of extra arguments. 

487 """ 

488 if annotation is not None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

489 if _typing_extra.is_annotated(annotation): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

490 first_arg, *extra_args = typing_extensions.get_args(annotation) 1bcdefghijklamnopqrstuvwxyzABCDEF

491 return first_arg, list(extra_args) 1bcdefghijklamnopqrstuvwxyzABCDEF

492 

493 return annotation, [] 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

494 

495 @staticmethod 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

497 """Collect annotations from kwargs. 

498 

499 Args: 

500 kwargs: Keyword arguments passed to the function. 

501 

502 Returns: 

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

504 `PydanticMetadata`. 

505 """ 

506 metadata: list[Any] = [] 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

507 general_metadata = {} 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

508 for key, value in list(kwargs.items()): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

509 try: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

510 marker = FieldInfo.metadata_lookup[key] 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

511 except KeyError: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

512 continue 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

513 

514 del kwargs[key] 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

515 if value is not None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

516 if marker is None: 1bcdefghijklamnopqrstuvwxyzABCDEF

517 general_metadata[key] = value 1bcdefghijklamnopqrstuvwxyzABCDEF

518 else: 

519 metadata.append(marker(value)) 1bcdefghijklamnopqrstuvwxyzABCDEF

520 if general_metadata: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

521 metadata.append(_fields.pydantic_general_metadata(**general_metadata)) 1bcdefghijklamnopqrstuvwxyzABCDEF

522 return metadata 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

523 

524 @property 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

525 def deprecation_message(self) -> str | None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

527 if self.deprecated is None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

528 return None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

529 if isinstance(self.deprecated, bool): 1bcdefghijklamnopqrstuvwxyzABCDEF

530 return 'deprecated' if self.deprecated else None 1bcdefghijklamnopqrstuvwxyzABCDEF

531 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1bcdefghijklamnopqrstuvwxyzABCDEF

532 

533 def get_default(self, *, call_default_factory: bool = False) -> Any: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

534 """Get the default value. 

535 

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

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

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

539 

540 Args: 

541 call_default_factory: Whether to call the default_factory or not. Defaults to `False`. 

542 

543 Returns: 

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

545 """ 

546 if self.default_factory is None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

547 return _utils.smart_deepcopy(self.default) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

548 elif call_default_factory: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

549 return self.default_factory() 1bcdefghijklamnopqrstuvwxyzABCDEF

550 else: 

551 return None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

552 

553 def is_required(self) -> bool: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

555 

556 Returns: 

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

558 """ 

559 return self.default is PydanticUndefined and self.default_factory is None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

560 

561 def rebuild_annotation(self) -> Any: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

563 

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

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

566 

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

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

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

570 

571 Returns: 

572 The rebuilt annotation. 

573 """ 

574 if not self.metadata: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

575 return self.annotation 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

576 else: 

577 # Annotated arguments must be a tuple 

578 return typing_extensions.Annotated[(self.annotation, *self.metadata)] # type: ignore 1bcdefghijklamnopqrstuvwxyzABCDEF

579 

580 def apply_typevars_map(self, typevars_map: dict[Any, Any] | None, types_namespace: dict[str, Any] | None) -> None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

582 

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

584 

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

586 

587 Args: 

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

589 types_namespace (dict | None): A dictionary containing related types to the annotated type. 

590 

591 See Also: 

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

593 their concrete types. 

594 """ 

595 annotation = _typing_extra.eval_type_lenient(self.annotation, types_namespace) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

596 self.annotation = _generics.replace_types(annotation, typevars_map) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

597 

598 def __repr_args__(self) -> ReprArgs: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

599 yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation)) 1bcdefghijklamnopqrstuvwxyzABCDEF

600 yield 'required', self.is_required() 1bcdefghijklamnopqrstuvwxyzABCDEF

601 

602 for s in self.__slots__: 1bcdefghijklamnopqrstuvwxyzABCDEF

603 if s == '_attributes_set': 1bcdefghijklamnopqrstuvwxyzABCDEF

604 continue 1bcdefghijklamnopqrstuvwxyzABCDEF

605 if s == 'annotation': 1bcdefghijklamnopqrstuvwxyzABCDEF

606 continue 1bcdefghijklamnopqrstuvwxyzABCDEF

607 elif s == 'metadata' and not self.metadata: 1bcdefghijklamnopqrstuvwxyzABCDEF

608 continue 1bcdefghijklamnopqrstuvwxyzABCDEF

609 elif s == 'repr' and self.repr is True: 1bcdefghijklamnopqrstuvwxyzABCDEF

610 continue 1bcdefghijklamnopqrstuvwxyzABCDEF

611 if s == 'frozen' and self.frozen is False: 1bcdefghijklamnopqrstuvwxyzABCDEF

612 continue 1bcdefghijklamnopqrstuvwxyzABCDEF

613 if s == 'validation_alias' and self.validation_alias == self.alias: 1bcdefghijklamnopqrstuvwxyzABCDEF

614 continue 1bcdefghijklamnopqrstuvwxyzABCDEF

615 if s == 'serialization_alias' and self.serialization_alias == self.alias: 1bcdefghijklamnopqrstuvwxyzABCDEF

616 continue 1bcdefghijklamnopqrstuvwxyzABCDEF

617 if s == 'default' and self.default is not PydanticUndefined: 1bcdefghijklamnopqrstuvwxyzABCDEF

618 yield 'default', self.default 1bcdefghijklamnopqrstuvwxyzABCDEF

619 elif s == 'default_factory' and self.default_factory is not None: 1bcdefghijklamnopqrstuvwxyzABCDEF

620 yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory)) 1bcdefghijklamnopqrstuvwxyzABCDEF

621 else: 

622 value = getattr(self, s) 1bcdefghijklamnopqrstuvwxyzABCDEF

623 if value is not None and value is not PydanticUndefined: 1bcdefghijklamnopqrstuvwxyzABCDEF

624 yield s, value 1bcdefghijklamnopqrstuvwxyzABCDEF

625 

626 

627class _EmptyKwargs(typing_extensions.TypedDict): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

629 

630 

631_DefaultValues = dict( 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

632 default=..., 

633 default_factory=None, 

634 alias=None, 

635 alias_priority=None, 

636 validation_alias=None, 

637 serialization_alias=None, 

638 title=None, 

639 description=None, 

640 examples=None, 

641 exclude=None, 

642 discriminator=None, 

643 json_schema_extra=None, 

644 frozen=None, 

645 validate_default=None, 

646 repr=True, 

647 init=None, 

648 init_var=None, 

649 kw_only=None, 

650 pattern=None, 

651 strict=None, 

652 gt=None, 

653 ge=None, 

654 lt=None, 

655 le=None, 

656 multiple_of=None, 

657 allow_inf_nan=None, 

658 max_digits=None, 

659 decimal_places=None, 

660 min_length=None, 

661 max_length=None, 

662 coerce_numbers_to_str=None, 

663) 

664 

665 

666def Field( # noqa: C901 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

667 default: Any = PydanticUndefined, 

668 *, 

669 default_factory: typing.Callable[[], Any] | None = _Unset, 

670 alias: str | None = _Unset, 

671 alias_priority: int | None = _Unset, 

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

673 serialization_alias: str | None = _Unset, 

674 title: str | None = _Unset, 

675 description: str | None = _Unset, 

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

677 exclude: bool | None = _Unset, 

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

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

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

681 frozen: bool | None = _Unset, 

682 validate_default: bool | None = _Unset, 

683 repr: bool = _Unset, 

684 init: bool | None = _Unset, 

685 init_var: bool | None = _Unset, 

686 kw_only: bool | None = _Unset, 

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

688 strict: bool | None = _Unset, 

689 coerce_numbers_to_str: bool | None = _Unset, 

690 gt: annotated_types.SupportsGt | None = _Unset, 

691 ge: annotated_types.SupportsGe | None = _Unset, 

692 lt: annotated_types.SupportsLt | None = _Unset, 

693 le: annotated_types.SupportsLe | None = _Unset, 

694 multiple_of: float | None = _Unset, 

695 allow_inf_nan: bool | None = _Unset, 

696 max_digits: int | None = _Unset, 

697 decimal_places: int | None = _Unset, 

698 min_length: int | None = _Unset, 

699 max_length: int | None = _Unset, 

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

701 **extra: Unpack[_EmptyKwargs], 

702) -> Any: 

703 """Usage docs: https://docs.pydantic.dev/2.8/concepts/fields 

704 

705 Create a field for objects that can be configured. 

706 

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

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

709 

710 Note: 

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

712 

713 Args: 

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

715 default_factory: A callable to generate the default value, such as :func:`~datetime.utcnow`. 

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

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

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

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

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

721 title: Human-readable title. 

722 description: Human-readable description. 

723 examples: Example values for this field. 

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

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

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

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

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

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

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

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

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

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

734 (Only applies to dataclasses.) 

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

736 (Only applies to dataclasses.) 

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

738 (Only applies to dataclasses.) 

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

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

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

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

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

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

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

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

747 min_length: Minimum length for iterables. 

748 max_length: Maximum length for iterables. 

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

750 allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to numbers. 

751 max_digits: Maximum number of allow digits for strings. 

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

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

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

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

756 

757 !!! warning Deprecated 

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

759 

760 Returns: 

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

762 type-annotated fields without causing a type error. 

763 """ 

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

765 const = extra.pop('const', None) # type: ignore 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

766 if const is not None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

768 

769 min_items = extra.pop('min_items', None) # type: ignore 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

770 if min_items is not None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

772 if min_length in (None, _Unset): 1bcdefghijklamnopqrstuvwxyzABCDEF

773 min_length = min_items # type: ignore 1bcdefghijklamnopqrstuvwxyzABCDEF

774 

775 max_items = extra.pop('max_items', None) # type: ignore 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

776 if max_items is not None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

778 if max_length in (None, _Unset): 1bcdefghijklamnopqrstuvwxyzABCDEF

779 max_length = max_items # type: ignore 1bcdefghijklamnopqrstuvwxyzABCDEF

780 

781 unique_items = extra.pop('unique_items', None) # type: ignore 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

782 if unique_items is not None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

783 raise PydanticUserError( 1bcdefghijklamnopqrstuvwxyzABCDEF

784 ( 

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

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

787 ), 

788 code='removed-kwargs', 

789 ) 

790 

791 allow_mutation = extra.pop('allow_mutation', None) # type: ignore 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

792 if allow_mutation is not None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

794 if allow_mutation is False: 1bcdefghijklamnopqrstuvwxyzABCDEF

795 frozen = True 1bcdefghijklamnopqrstuvwxyzABCDEF

796 

797 regex = extra.pop('regex', None) # type: ignore 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

798 if regex is not None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

800 

801 if extra: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

802 warn( 1bcdefghijklamnopqrstuvwxyzABCDEF

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

804 ' Use `json_schema_extra` instead.' 

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

806 DeprecationWarning, 

807 ) 

808 if not json_schema_extra or json_schema_extra is _Unset: 1bcdefghijklamnopqrstuvwxyzABCDEF

809 json_schema_extra = extra # type: ignore 1bcdefghijklamnopqrstuvwxyzABCDEF

810 

811 if ( 1bcdefghilamnopqrstGHIJKLMNwxyzABCD

812 validation_alias 

813 and validation_alias is not _Unset 

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

815 ): 

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

817 

818 if serialization_alias in (_Unset, None) and isinstance(alias, str): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

819 serialization_alias = alias 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

820 

821 if validation_alias in (_Unset, None): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

822 validation_alias = alias 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

823 

824 include = extra.pop('include', None) # type: ignore 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

825 if include is not None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

827 

828 return FieldInfo.from_field( 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

829 default, 

830 default_factory=default_factory, 

831 alias=alias, 

832 alias_priority=alias_priority, 

833 validation_alias=validation_alias, 

834 serialization_alias=serialization_alias, 

835 title=title, 

836 description=description, 

837 examples=examples, 

838 exclude=exclude, 

839 discriminator=discriminator, 

840 deprecated=deprecated, 

841 json_schema_extra=json_schema_extra, 

842 frozen=frozen, 

843 pattern=pattern, 

844 validate_default=validate_default, 

845 repr=repr, 

846 init=init, 

847 init_var=init_var, 

848 kw_only=kw_only, 

849 coerce_numbers_to_str=coerce_numbers_to_str, 

850 strict=strict, 

851 gt=gt, 

852 ge=ge, 

853 lt=lt, 

854 le=le, 

855 multiple_of=multiple_of, 

856 min_length=min_length, 

857 max_length=max_length, 

858 allow_inf_nan=allow_inf_nan, 

859 max_digits=max_digits, 

860 decimal_places=decimal_places, 

861 union_mode=union_mode, 

862 ) 

863 

864 

865_FIELD_ARG_NAMES = set(inspect.signature(Field).parameters) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

866_FIELD_ARG_NAMES.remove('extra') # do not include the varkwargs parameter 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

867 

868 

869class ModelPrivateAttr(_repr.Representation): 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

871 

872 !!! warning 

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

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

875 

876 Attributes: 

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

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

879 attribute if not provided. 

880 """ 

881 

882 __slots__ = 'default', 'default_factory' 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

883 

884 def __init__( 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

886 ) -> None: 

887 self.default = default 1bcdefghijklamnopqrstuvwxyzABCDEF

888 self.default_factory = default_factory 1bcdefghijklamnopqrstuvwxyzABCDEF

889 

890 if not typing.TYPE_CHECKING: 890 ↛ 902line 890 didn't jump to line 902, because the condition on line 890 was always true1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

892 

893 def __getattr__(self, item: str) -> Any: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

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

896 """ 

897 if item in {'__get__', '__set__', '__delete__'}: 1bcdefghijklamnopqrstuvwxyzABCDEF

898 if hasattr(self.default, item): 1bcdefghijklamnopqrstuvwxyzABCDEF

899 return getattr(self.default, item) 1bcdefghijklamnopqrstuvwxyzABCDEF

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

901 

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

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

904 if self.default is PydanticUndefined: 1bcdefghijklamnopqrstuvwxyzABCDEF

905 return 1bcdefghijklamnopqrstuvwxyzABCDEF

906 if not hasattr(self.default, '__set_name__'): 1bcdefghijklamnopqrstuvwxyzABCDEF

907 return 1bcdefghijklamnopqrstuvwxyzABCDEF

908 set_name = self.default.__set_name__ 1bcdefghijklamnopqrstuvwxyzABCDEF

909 if callable(set_name): 1bcdefghijklamnopqrstuvwxyzABCDEF

910 set_name(cls, name) 1bcdefghijklamnopqrstuvwxyzABCDEF

911 

912 def get_default(self) -> Any: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

914 

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

916 

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

918 

919 Returns: 

920 The default value of the object. 

921 """ 

922 return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() 1bcdefghijklamnopqrstuvwxyzABCDEF

923 

924 def __eq__(self, other: Any) -> bool: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

925 return isinstance(other, self.__class__) and (self.default, self.default_factory) == ( 1bcdefghijklamnopqrstuvwxyzABCDEF

926 other.default, 

927 other.default_factory, 

928 ) 

929 

930 

931def PrivateAttr( 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

932 default: Any = PydanticUndefined, 

933 *, 

934 default_factory: typing.Callable[[], Any] | None = None, 

935 init: Literal[False] = False, 

936) -> Any: 

937 """Usage docs: https://docs.pydantic.dev/2.8/concepts/models/#private-model-attributes 

938 

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

940 

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

942 

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

944 

945 Args: 

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

947 default_factory: Callable that will be 

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

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

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

951 

952 Returns: 

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

954 

955 Raises: 

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

957 """ 

958 if default is not PydanticUndefined and default_factory is not None: 1bcdefghijklamnopqrstuvwxyzABCDEF

959 raise TypeError('cannot specify both default and default_factory') 1bcdefghijklamnopqrstuvwxyzABCDEF

960 

961 return ModelPrivateAttr( 1bcdefghijklamnopqrstuvwxyzABCDEF

962 default, 

963 default_factory=default_factory, 

964 ) 

965 

966 

967@dataclasses.dataclass(**_internal_dataclass.slots_true) 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

968class ComputedFieldInfo: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

970 

971 Attributes: 

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

973 wrapped_property: The wrapped computed field property. 

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

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

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

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

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

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

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

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

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

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

984 """ 

985 

986 decorator_repr: ClassVar[str] = '@computed_field' 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

987 wrapped_property: property 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

988 return_type: Any 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

989 alias: str | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

990 alias_priority: int | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

991 title: str | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

992 description: str | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

993 deprecated: Deprecated | str | bool | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

994 examples: list[Any] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

995 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

996 repr: bool 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

997 

998 @property 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

999 def deprecation_message(self) -> str | None: 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

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

1001 if self.deprecated is None: 1bcdefghijklamnopqrstuvwxyzABCDEF

1002 return None 1bcdefghijklamnopqrstuvwxyzABCDEF

1003 if isinstance(self.deprecated, bool): 1bcdefghijklamnopqrstuvwxyzABCDEF

1004 return 'deprecated' if self.deprecated else None 1bcdefghijklamnopqrstuvwxyzABCDEF

1005 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1bcdefghijklamnopqrstuvwxyzABCDEF

1006 

1007 

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

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

1010 wrapped_name: str = '' 1bcdefghijklamnopqrstuvwxyzABCDEF

1011 

1012 if isinstance(property_, property): 1bcdefghijklamnopqrstuvwxyzABCDEF

1013 wrapped_name = getattr(property_.fget, '__name__', '') 1bcdefghijklamnopqrstuvwxyzABCDEF

1014 elif isinstance(property_, cached_property): # type: ignore 1bcdefghijklamnopqrstuvwxyzABCDEF

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

1016 

1017 return wrapped_name.startswith('_') and not wrapped_name.startswith('__') 1bcdefghijklamnopqrstuvwxyzABCDEF

1018 

1019 

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

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

1022PropertyT = typing.TypeVar('PropertyT') 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1023 

1024 

1025@typing.overload 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1026def computed_field( 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1027 *, 

1028 alias: str | None = None, 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1029 alias_priority: int | None = None, 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1030 title: str | None = None, 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1031 description: str | None = None, 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1032 deprecated: Deprecated | str | bool | None = None, 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1033 examples: list[Any] | None = None, 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1034 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None, 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1035 repr: bool = True, 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1036 return_type: Any = PydanticUndefined, 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1037) -> typing.Callable[[PropertyT], PropertyT]: ... 1jklauvOEF

1038 

1039 

1040@typing.overload 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1041def computed_field(__func: PropertyT) -> PropertyT: ... 1bcdefghijklamnopqrstuvGHIJKLMNOwxyzABCDEF

1042 

1043 

1044def computed_field( 1bcdefghijkmnopqrstuvGHIJKLMNOwxyzABCDEF

1045 func: PropertyT | None = None, 

1046 /, 

1047 *, 

1048 alias: str | None = None, 

1049 alias_priority: int | None = None, 

1050 title: str | None = None, 

1051 description: str | None = None, 

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

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

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

1055 repr: bool | None = None, 

1056 return_type: Any = PydanticUndefined, 

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

1058 """Usage docs: https://docs.pydantic.dev/2.8/concepts/fields#the-computed_field-decorator 

1059 

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

1061 

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

1063 

1064 ```py 

1065 from pydantic import BaseModel, computed_field 

1066 

1067 class Rectangle(BaseModel): 

1068 width: int 

1069 length: int 

1070 

1071 @computed_field 

1072 @property 

1073 def area(self) -> int: 

1074 return self.width * self.length 

1075 

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

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

1078 ``` 

1079 

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

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

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

1083 

1084 !!! warning "Mypy Warning" 

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

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

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

1088 To avoid this error message, add `# type: ignore[misc]` to the `@computed_field` line. 

1089 

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

1091 

1092 ```py 

1093 import random 

1094 

1095 from pydantic import BaseModel, computed_field 

1096 

1097 class Square(BaseModel): 

1098 width: float 

1099 

1100 @computed_field 

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

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

1103 

1104 @area.setter 

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

1106 self.width = new_area**0.5 

1107 

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

1109 def random_number(self) -> int: 

1110 return random.randint(0, 1_000) 

1111 

1112 square = Square(width=1.3) 

1113 

1114 # `random_number` does not appear in representation 

1115 print(repr(square)) 

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

1117 

1118 print(square.random_number) 

1119 #> 3 

1120 

1121 square.area = 4 

1122 

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

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

1125 ``` 

1126 

1127 !!! warning "Overriding with `computed_field`" 

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

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

1130 See the example below: 

1131 

1132 ```py 

1133 from pydantic import BaseModel, computed_field 

1134 

1135 class Parent(BaseModel): 

1136 a: str 

1137 

1138 try: 

1139 

1140 class Child(Parent): 

1141 @computed_field 

1142 @property 

1143 def a(self) -> str: 

1144 return 'new a' 

1145 

1146 except ValueError as e: 

1147 print(repr(e)) 

1148 #> ValueError("you can't override a field with a computed field") 

1149 ``` 

1150 

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

1152 

1153 ```py 

1154 from functools import cached_property 

1155 

1156 from pydantic import BaseModel, computed_field 

1157 

1158 class Model(BaseModel): 

1159 foo: int 

1160 

1161 @computed_field 

1162 @cached_property 

1163 def _private_cached_property(self) -> int: 

1164 return -self.foo 

1165 

1166 @computed_field 

1167 @property 

1168 def _private_property(self) -> int: 

1169 return -self.foo 

1170 

1171 m = Model(foo=1) 

1172 print(repr(m)) 

1173 #> M(foo=1) 

1174 ``` 

1175 

1176 Args: 

1177 func: the function to wrap. 

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

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

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

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

1182 docstring 

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

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

1185 `deprecated` decorator. 

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

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

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

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

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

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

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

1193 objects. 

1194 

1195 Returns: 

1196 A proxy wrapper for the property. 

1197 """ 

1198 

1199 def dec(f: Any) -> Any: 1bcdefghijklamnopqrstuvwxyzABCDEF

1200 nonlocal description, deprecated, return_type, alias_priority 

1201 unwrapped = _decorators.unwrap_wrapped_function(f) 1bcdefghijklamnopqrstuvwxyzABCDEF

1202 

1203 if description is None and unwrapped.__doc__: 1bcdefghijklamnopqrstuvwxyzABCDEF

1204 description = inspect.cleandoc(unwrapped.__doc__) 1bcdefghijklamnopqrstuvwxyzABCDEF

1205 

1206 if deprecated is None and hasattr(unwrapped, '__deprecated__'): 1bcdefghijklamnopqrstuvwxyzABCDEF

1207 deprecated = unwrapped.__deprecated__ 1bcdefghijklamnopqrstuvwxyzABCDEF

1208 

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

1210 f = _decorators.ensure_property(f) 1bcdefghijklamnopqrstuvwxyzABCDEF

1211 alias_priority = (alias_priority or 2) if alias is not None else None 1bcdefghijklamnopqrstuvwxyzABCDEF

1212 

1213 if repr is None: 1bcdefghijklamnopqrstuvwxyzABCDEF

1214 repr_: bool = not _wrapped_property_is_private(property_=f) 1bcdefghijklamnopqrstuvwxyzABCDEF

1215 else: 

1216 repr_ = repr 1bcdefghijklamnopqrstuvwxyzABCDEF

1217 

1218 dec_info = ComputedFieldInfo( 1bcdefghijklamnopqrstuvwxyzABCDEF

1219 f, 

1220 return_type, 

1221 alias, 

1222 alias_priority, 

1223 title, 

1224 description, 

1225 deprecated, 

1226 examples, 

1227 json_schema_extra, 

1228 repr_, 

1229 ) 

1230 return _decorators.PydanticDescriptorProxy(f, dec_info) 1bcdefghijklamnopqrstuvwxyzABCDEF

1231 

1232 if func is None: 1bcdefghijklamnopqrstuvwxyzABCDEF

1233 return dec 1bcdefghijklamnopqrstuvwxyzABCDEF

1234 else: 

1235 return dec(func) 1bcdefghijklamnopqrstuvwxyzABCDEF