Coverage for pydantic/fields.py: 98.88%

445 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-02-13 19:35 +0000

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

2 

3from __future__ import annotations as _annotations 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

4 

5import dataclasses 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

6import inspect 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

7import sys 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

8import typing 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

9from collections.abc import Mapping 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

10from copy import copy 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

11from dataclasses import Field as DataclassField 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

12from functools import cached_property 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

13from typing import Annotated, Any, Callable, ClassVar, Literal, TypeVar, cast, overload 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

14from warnings import warn 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

15 

16import annotated_types 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

17import typing_extensions 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

18from pydantic_core import PydanticUndefined 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

19from typing_extensions import TypeAlias, Unpack, deprecated 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

20 

21from . import types 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

22from ._internal import _decorators, _fields, _generics, _internal_dataclass, _repr, _typing_extra, _utils 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

23from ._internal._namespace_utils import GlobalsNamespace, MappingNamespace 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

24from .aliases import AliasChoices, AliasPath 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

25from .config import JsonDict 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

26from .errors import PydanticUserError 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

27from .json_schema import PydanticJsonSchemaWarning 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

28from .warnings import PydanticDeprecatedSince20 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

29 

30if typing.TYPE_CHECKING: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

31 from ._internal._repr import ReprArgs 1i

32else: 

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

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

35 DeprecationWarning = PydanticDeprecatedSince20 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

36 

37__all__ = 'Field', 'PrivateAttr', 'computed_field' 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

38 

39 

40_Unset: Any = PydanticUndefined 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

41 

42if sys.version_info >= (3, 13): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

43 import warnings 1abcdGef

44 

45 Deprecated: TypeAlias = warnings.deprecated | deprecated 1abcdGef

46else: 

47 Deprecated: TypeAlias = deprecated 1opqrstghniuvwxyzjkKLMHIJABCDEFlm

48 

49 

50class _FromFieldInfoInputs(typing_extensions.TypedDict, total=False): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

52 

53 # TODO PEP 747: use TypeForm: 

54 annotation: type[Any] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

55 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

56 alias: str | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

57 alias_priority: int | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

58 validation_alias: str | AliasPath | AliasChoices | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

59 serialization_alias: str | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

60 title: str | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

61 field_title_generator: Callable[[str, FieldInfo], str] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

62 description: str | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

63 examples: list[Any] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

64 exclude: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

65 gt: annotated_types.SupportsGt | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

66 ge: annotated_types.SupportsGe | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

67 lt: annotated_types.SupportsLt | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

68 le: annotated_types.SupportsLe | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

69 multiple_of: float | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

70 strict: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

71 min_length: int | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

72 max_length: int | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

73 pattern: str | typing.Pattern[str] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

74 allow_inf_nan: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

75 max_digits: int | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

76 decimal_places: int | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

77 union_mode: Literal['smart', 'left_to_right'] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

78 discriminator: str | types.Discriminator | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

79 deprecated: Deprecated | str | bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

80 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

81 frozen: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

82 validate_default: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

83 repr: bool 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

84 init: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

85 init_var: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

86 kw_only: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

87 coerce_numbers_to_str: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

88 fail_fast: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

89 

90 

91class _FieldInfoInputs(_FromFieldInfoInputs, total=False): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

93 

94 default: Any 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

95 

96 

97class FieldInfo(_repr.Representation): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

99 

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

101 function is explicitly used. 

102 

103 !!! warning 

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

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

106 

107 Attributes: 

108 annotation: The type annotation of the field. 

109 default: The default value of the field. 

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

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

112 alias: The alias name of the field. 

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

114 validation_alias: The validation alias of the field. 

115 serialization_alias: The serialization alias of the field. 

116 title: The title of the field. 

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

118 description: The description of the field. 

119 examples: List of examples of the field. 

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

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

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

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

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

125 frozen: Whether the field is frozen. 

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

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

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

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

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

131 metadata: List of metadata constraints. 

132 """ 

133 

134 annotation: type[Any] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

135 default: Any 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

136 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

137 alias: str | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

138 alias_priority: int | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

139 validation_alias: str | AliasPath | AliasChoices | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

140 serialization_alias: str | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

141 title: str | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

142 field_title_generator: Callable[[str, FieldInfo], str] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

143 description: str | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

144 examples: list[Any] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

145 exclude: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

146 discriminator: str | types.Discriminator | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

147 deprecated: Deprecated | str | bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

148 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

149 frozen: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

150 validate_default: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

151 repr: bool 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

152 init: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

153 init_var: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

154 kw_only: bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

155 metadata: list[Any] 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

156 

157 __slots__ = ( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

158 'annotation', 

159 'default', 

160 'default_factory', 

161 'alias', 

162 'alias_priority', 

163 'validation_alias', 

164 'serialization_alias', 

165 'title', 

166 'field_title_generator', 

167 'description', 

168 'examples', 

169 'exclude', 

170 'discriminator', 

171 'deprecated', 

172 'json_schema_extra', 

173 'frozen', 

174 'validate_default', 

175 'repr', 

176 'init', 

177 'init_var', 

178 'kw_only', 

179 'metadata', 

180 '_attributes_set', 

181 '_complete', 

182 '_original_assignment', 

183 '_original_annotation', 

184 ) 

185 

186 # used to convert kwargs to metadata/constraints, 

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

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

189 'strict': types.Strict, 

190 'gt': annotated_types.Gt, 

191 'ge': annotated_types.Ge, 

192 'lt': annotated_types.Lt, 

193 'le': annotated_types.Le, 

194 'multiple_of': annotated_types.MultipleOf, 

195 'min_length': annotated_types.MinLen, 

196 'max_length': annotated_types.MaxLen, 

197 'pattern': None, 

198 'allow_inf_nan': None, 

199 'max_digits': None, 

200 'decimal_places': None, 

201 'union_mode': None, 

202 'coerce_numbers_to_str': None, 

203 'fail_fast': types.FailFast, 

204 } 

205 

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

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

208 or one of the constructor classmethods. 

209 

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

211 """ 

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

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

214 self.annotation = kwargs.get('annotation') 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

215 

216 default = kwargs.pop('default', PydanticUndefined) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

217 if default is Ellipsis: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

218 self.default = PydanticUndefined 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

219 self._attributes_set.pop('default', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

220 else: 

221 self.default = default 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

222 

223 self.default_factory = kwargs.pop('default_factory', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

224 

225 if self.default is not PydanticUndefined and self.default_factory is not None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

226 raise TypeError('cannot specify both default and default_factory') 1opqrstghabniuvwxyzjkcdABCDEFlmef

227 

228 self.alias = kwargs.pop('alias', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

229 self.validation_alias = kwargs.pop('validation_alias', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

230 self.serialization_alias = kwargs.pop('serialization_alias', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

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

233 self.title = kwargs.pop('title', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

234 self.field_title_generator = kwargs.pop('field_title_generator', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

235 self.description = kwargs.pop('description', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

236 self.examples = kwargs.pop('examples', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

237 self.exclude = kwargs.pop('exclude', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

238 self.discriminator = kwargs.pop('discriminator', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

240 self.deprecated = kwargs.pop('deprecated', getattr(self, 'deprecated', None)) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

241 self.repr = kwargs.pop('repr', True) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

242 self.json_schema_extra = kwargs.pop('json_schema_extra', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

243 self.validate_default = kwargs.pop('validate_default', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

244 self.frozen = kwargs.pop('frozen', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

245 # currently only used on dataclasses 

246 self.init = kwargs.pop('init', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

247 self.init_var = kwargs.pop('init_var', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

248 self.kw_only = kwargs.pop('kw_only', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

249 

250 self.metadata = self._collect_metadata(kwargs) # type: ignore 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

251 

252 # Private attributes, used to rebuild FieldInfo instances: 

253 self._complete = True 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

254 self._original_annotation: Any = PydanticUndefined 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

255 self._original_assignment: Any = PydanticUndefined 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

256 

257 @staticmethod 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

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

260 

261 Args: 

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

263 **kwargs: Additional arguments dictionary. 

264 

265 Raises: 

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

267 

268 Returns: 

269 A new FieldInfo object with the given parameters. 

270 

271 Example: 

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

273 

274 ```python 

275 import pydantic 

276 

277 class MyModel(pydantic.BaseModel): 

278 foo: int = pydantic.Field(4) 

279 ``` 

280 """ 

281 if 'annotation' in kwargs: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

283 return FieldInfo(default=default, **kwargs) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

284 

285 @staticmethod 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

286 def from_annotation(annotation: type[Any]) -> FieldInfo: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

288 

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

290 

291 ```python 

292 import pydantic 

293 

294 class MyModel(pydantic.BaseModel): 

295 foo: int # <-- like this 

296 ``` 

297 

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

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

300 

301 ```python 

302 from typing import Annotated 

303 

304 import annotated_types 

305 

306 import pydantic 

307 

308 class MyModel(pydantic.BaseModel): 

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

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

311 ``` 

312 

313 Args: 

314 annotation: An annotation object. 

315 

316 Returns: 

317 An instance of the field metadata. 

318 """ 

319 # 1. Check if the annotation is the `Final` type qualifier: 

320 final = _typing_extra.is_finalvar(annotation) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

321 if final: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

322 if _typing_extra.is_generic_alias(annotation): 1opqrstghabniuvwxyzjkcdABCDEFlmef

323 # 1.1. The annotation is a parametrized `Final`, e.g. `Final[int]`. 

324 # In this case, `annotation` will be `int`: 

325 annotation = typing_extensions.get_args(annotation)[0] 1opqrstghabniuvwxyzjkcdABCDEFlmef

326 else: 

327 # 1.2. The annotation is a bare `Final`. Use `Any` as a type annotation: 

328 return FieldInfo(annotation=Any, frozen=True) # pyright: ignore[reportArgumentType] (PEP 747) 1opqrstghabniuvwxyzjkcdABCDEFlmef

329 

330 # 2. Check if the annotation is an `Annotated` form. 

331 # In this case, `annotation` will be the annotated type: 

332 annotation, metadata = _typing_extra.unpack_annotated(annotation) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

333 

334 # 3. If we have metadata, `annotation` was the annotated type: 

335 if metadata: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

336 # 3.1. Check if the annotated type is the `Final` type qualifier. 

337 # (i.e. `Annotated[Final[...], ...]`). Note that we only do 

338 # so if `final` isn't `True` already, because we don't want to 

339 # support the invalid `Final[Annotated[Final, ...]]` form. 

340 if not final: 1opqrstghabniuvwxyzjkcdABCDEFlmef

341 final = _typing_extra.is_finalvar(annotation) 1opqrstghabniuvwxyzjkcdABCDEFlmef

342 if final and _typing_extra.is_generic_alias(annotation): 1opqrstghabniuvwxyzjkcdABCDEFlmef

343 annotation = typing_extensions.get_args(annotation)[0] 1opqrstghabniuvwxyzjkcdABCDEFlmef

344 

345 field_info_annotations = [a for a in metadata if isinstance(a, FieldInfo)] 1opqrstghabniuvwxyzjkcdABCDEFlmef

346 field_info = FieldInfo.merge_field_infos(*field_info_annotations, annotation=annotation) 1opqrstghabniuvwxyzjkcdABCDEFlmef

347 if field_info: 347 ↛ 363line 347 didn't jump to line 363 because the condition on line 347 was always true1opqrstghabniuvwxyzjkcdABCDEFlmef

348 new_field_info = copy(field_info) 1opqrstghabniuvwxyzjkcdABCDEFlmef

349 new_field_info.annotation = annotation 1opqrstghabniuvwxyzjkcdABCDEFlmef

350 new_field_info.frozen = final or field_info.frozen 1opqrstghabniuvwxyzjkcdABCDEFlmef

351 field_metadata: list[Any] = [] 1opqrstghabniuvwxyzjkcdABCDEFlmef

352 for a in metadata: 1opqrstghabniuvwxyzjkcdABCDEFlmef

353 if _typing_extra.is_deprecated_instance(a): 1opqrstghabniuvwxyzjkcdABCDEFlmef

354 new_field_info.deprecated = a.message 1opqrstghabniuvwxyzjkcdABCDEFlmef

355 elif not isinstance(a, FieldInfo): 1opqrstghabniuvwxyzjkcdABCDEFlmef

356 field_metadata.append(a) 1opqrstghabniuvwxyzjkcdABCDEFlmef

357 else: 

358 field_metadata.extend(a.metadata) 1opqrstghabniuvwxyzjkcdABCDEFlmef

359 new_field_info.metadata = field_metadata 1opqrstghabniuvwxyzjkcdABCDEFlmef

360 return new_field_info 1opqrstghabniuvwxyzjkcdABCDEFlmef

361 

362 # 4. We don't have metadata: 

363 return FieldInfo(annotation=annotation, frozen=final or None) # pyright: ignore[reportArgumentType] (PEP 747) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

364 

365 @staticmethod 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

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

368 

369 This is used in cases like the following: 

370 

371 ```python 

372 from typing import Annotated 

373 

374 import annotated_types 

375 

376 import pydantic 

377 

378 class MyModel(pydantic.BaseModel): 

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

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

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

382 ``` 

383 

384 Args: 

385 annotation: The type annotation of the field. 

386 default: The default value of the field. 

387 

388 Returns: 

389 A field object with the passed values. 

390 """ 

391 if annotation is default: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

392 raise PydanticUserError( 1opqrstghabniuvwxyzjkcdABCDEFlmef

393 'Error when building FieldInfo from annotated attribute. ' 

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

395 code='unevaluable-type-annotation', 

396 ) 

397 

398 final = _typing_extra.is_finalvar(annotation) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

399 if final and _typing_extra.is_generic_alias(annotation): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

400 annotation = typing_extensions.get_args(annotation)[0] 1opqrstghabniuvwxyzjkcdABCDEFlmef

401 

402 if isinstance(default, FieldInfo): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

403 default.annotation, annotation_metadata = _typing_extra.unpack_annotated(annotation) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

404 default.metadata += annotation_metadata 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

405 default = default.merge_field_infos( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

407 ) 

408 default.frozen = final or default.frozen 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

409 return default 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

410 

411 if isinstance(default, dataclasses.Field): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

412 init_var = False 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

413 if annotation is dataclasses.InitVar: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

414 init_var = True 1opqrstghabniuvwxyzjkcdABCDEFlmef

415 annotation = typing.cast(Any, Any) 1opqrstghabniuvwxyzjkcdABCDEFlmef

416 elif isinstance(annotation, dataclasses.InitVar): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

417 init_var = True 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

418 annotation = annotation.type 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

419 

420 pydantic_field = FieldInfo._from_dataclass_field(default) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

421 pydantic_field.annotation, annotation_metadata = _typing_extra.unpack_annotated(annotation) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

422 pydantic_field.metadata += annotation_metadata 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

423 pydantic_field = pydantic_field.merge_field_infos( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

425 pydantic_field, 

426 annotation=pydantic_field.annotation, 

427 ) 

428 pydantic_field.frozen = final or pydantic_field.frozen 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

429 pydantic_field.init_var = init_var 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

430 pydantic_field.init = getattr(default, 'init', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

431 pydantic_field.kw_only = getattr(default, 'kw_only', None) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

432 return pydantic_field 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

433 

434 annotation, metadata = _typing_extra.unpack_annotated(annotation) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

435 

436 if metadata: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

437 field_infos = [a for a in metadata if isinstance(a, FieldInfo)] 1opqrstghabniuvwxyzjkcdABCDEFlmef

438 field_info = FieldInfo.merge_field_infos(*field_infos, annotation=annotation, default=default) 1opqrstghabniuvwxyzjkcdABCDEFlmef

439 field_metadata: list[Any] = [] 1opqrstghabniuvwxyzjkcdABCDEFlmef

440 for a in metadata: 1opqrstghabniuvwxyzjkcdABCDEFlmef

441 if _typing_extra.is_deprecated_instance(a): 1opqrstghabniuvwxyzjkcdABCDEFlmef

442 field_info.deprecated = a.message 1opqrstghabniuvwxyzjkcdABCDEFlmef

443 elif not isinstance(a, FieldInfo): 1opqrstghabniuvwxyzjkcdABCDEFlmef

444 field_metadata.append(a) 1opqrstghabniuvwxyzjkcdABCDEFlmef

445 else: 

446 field_metadata.extend(a.metadata) 1opqrstghabniuvwxyzjkcdABCDEFlmef

447 field_info.metadata = field_metadata 1opqrstghabniuvwxyzjkcdABCDEFlmef

448 return field_info 1opqrstghabniuvwxyzjkcdABCDEFlmef

449 

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

451 

452 @staticmethod 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

453 def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

455 

456 Later `FieldInfo` instances override earlier ones. 

457 

458 Returns: 

459 FieldInfo: A merged FieldInfo instance. 

460 """ 

461 if len(field_infos) == 1: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

463 field_info = copy(field_infos[0]) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

464 field_info._attributes_set.update(overrides) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

465 

466 default_override = overrides.pop('default', PydanticUndefined) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

467 if default_override is Ellipsis: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

468 default_override = PydanticUndefined 1opqrstghabniuvwxyzjkcdABCDEFlmef

469 if default_override is not PydanticUndefined: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

470 field_info.default = default_override 1opqrstghabniuvwxyzjkcdABCDEFlmef

471 

472 for k, v in overrides.items(): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

473 setattr(field_info, k, v) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

474 return field_info # type: ignore 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

475 

476 merged_field_info_kwargs: dict[str, Any] = {} 1opqrstghabniuvwxyzjkcdABCDEFlmef

477 metadata = {} 1opqrstghabniuvwxyzjkcdABCDEFlmef

478 for field_info in field_infos: 1opqrstghabniuvwxyzjkcdABCDEFlmef

479 attributes_set = field_info._attributes_set.copy() 1opqrstghabniuvwxyzjkcdABCDEFlmef

480 

481 try: 1opqrstghabniuvwxyzjkcdABCDEFlmef

482 json_schema_extra = attributes_set.pop('json_schema_extra') 1opqrstghabniuvwxyzjkcdABCDEFlmef

483 existing_json_schema_extra = merged_field_info_kwargs.get('json_schema_extra') 1opqrstghabniuvwxyzjkcdABCDEFlmef

484 

485 if existing_json_schema_extra is None: 1opqrstghabniuvwxyzjkcdABCDEFlmef

486 merged_field_info_kwargs['json_schema_extra'] = json_schema_extra 1opqrstghabniuvwxyzjkcdABCDEFlmef

487 if isinstance(existing_json_schema_extra, dict): 1opqrstghabniuvwxyzjkcdABCDEFlmef

488 if isinstance(json_schema_extra, dict): 1opqrstghabniuvwxyzjkcdABCDEFlmef

489 merged_field_info_kwargs['json_schema_extra'] = { 1opqrstghabniuvwxyzjkcdABCDEFlmef

490 **existing_json_schema_extra, 

491 **json_schema_extra, 

492 } 

493 if callable(json_schema_extra): 1opqrstghabniuvwxyzjkcdABCDEFlmef

494 warn( 1opqrstghabniuvwxyzjkcdABCDEFlmef

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 PydanticJsonSchemaWarning, 

499 ) 

500 elif callable(json_schema_extra): 1opqrstghabniuvwxyzjkcdABCDEFlmef

501 # if ever there's a case of a callable, we'll just keep the last json schema extra spec 

502 merged_field_info_kwargs['json_schema_extra'] = json_schema_extra 1opqrstghabniuvwxyzjkcdABCDEFlmef

503 except KeyError: 1opqrstghabniuvwxyzjkcdABCDEFlmef

504 pass 1opqrstghabniuvwxyzjkcdABCDEFlmef

505 

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

507 merged_field_info_kwargs.update(attributes_set) 1opqrstghabniuvwxyzjkcdABCDEFlmef

508 

509 for x in field_info.metadata: 1opqrstghabniuvwxyzjkcdABCDEFlmef

510 if not isinstance(x, FieldInfo): 1opqrstghabniuvwxyzjkcdABCDEFlmef

511 metadata[type(x)] = x 1opqrstghabniuvwxyzjkcdABCDEFlmef

512 

513 merged_field_info_kwargs.update(overrides) 1opqrstghabniuvwxyzjkcdABCDEFlmef

514 field_info = FieldInfo(**merged_field_info_kwargs) 1opqrstghabniuvwxyzjkcdABCDEFlmef

515 field_info.metadata = list(metadata.values()) 1opqrstghabniuvwxyzjkcdABCDEFlmef

516 return field_info 1opqrstghabniuvwxyzjkcdABCDEFlmef

517 

518 @staticmethod 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

519 def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

521 

522 Args: 

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

524 

525 Returns: 

526 The corresponding `FieldInfo` instance. 

527 

528 Raises: 

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

530 """ 

531 default = dc_field.default 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

532 if default is dataclasses.MISSING: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

533 default = _Unset 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

534 

535 if dc_field.default_factory is dataclasses.MISSING: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

536 default_factory = _Unset 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

537 else: 

538 default_factory = dc_field.default_factory 1opqrstghabniuvwxyzjkcdABCDEFlmef

539 

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

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

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

543 

544 @staticmethod 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

546 """Collect annotations from kwargs. 

547 

548 Args: 

549 kwargs: Keyword arguments passed to the function. 

550 

551 Returns: 

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

553 `PydanticMetadata`. 

554 """ 

555 metadata: list[Any] = [] 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

556 general_metadata = {} 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

557 for key, value in list(kwargs.items()): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

558 try: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

559 marker = FieldInfo.metadata_lookup[key] 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

560 except KeyError: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

561 continue 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

562 

563 del kwargs[key] 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

564 if value is not None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

565 if marker is None: 1opqrstghabniuvwxyzjkcdABCDEFlmef

566 general_metadata[key] = value 1opqrstghabniuvwxyzjkcdABCDEFlmef

567 else: 

568 metadata.append(marker(value)) 1opqrstghabniuvwxyzjkcdABCDEFlmef

569 if general_metadata: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

570 metadata.append(_fields.pydantic_general_metadata(**general_metadata)) 1opqrstghabniuvwxyzjkcdABCDEFlmef

571 return metadata 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

572 

573 @property 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

574 def deprecation_message(self) -> str | None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

576 if self.deprecated is None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

577 return None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

578 if isinstance(self.deprecated, bool): 1opqrstghabniuvwxyzjkcdABCDEFlmef

579 return 'deprecated' if self.deprecated else None 1opqrstghabniuvwxyzjkcdABCDEFlmef

580 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1opqrstghabniuvwxyzjkcdABCDEFlmef

581 

582 @property 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

583 def default_factory_takes_validated_data(self) -> bool | None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

585 

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

587 """ 

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

589 return _fields.takes_validated_data_argument(self.default_factory) 1opqrstghabniuvwxyzjkcdABCDEFlmef

590 

591 @overload 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

592 def get_default( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

594 ) -> Any: ... 1ghabnijkcdHIJGlmef

595 

596 @overload 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

598 

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

600 """Get the default value. 

601 

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

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

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

605 

606 Args: 

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

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

609 

610 Returns: 

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

612 """ 

613 if self.default_factory is None: 1opqrstghabniuvwxyzjkcdABCDEFlmef

614 return _utils.smart_deepcopy(self.default) 1opqrstghabniuvwxyzjkcdABCDEFlmef

615 elif call_default_factory: 615 ↛ 627line 615 didn't jump to line 627 because the condition on line 615 was always true1opqrstghabniuvwxyzjkcdABCDEFlmef

616 if self.default_factory_takes_validated_data: 1opqrstghabniuvwxyzjkcdABCDEFlmef

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

618 if validated_data is None: 618 ↛ 619line 618 didn't jump to line 619 because the condition on line 618 was never true1opqrstghabniuvwxyzjkcdABCDEFlmef

619 raise ValueError( 

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

621 ) 

622 return fac(validated_data) 1opqrstghabniuvwxyzjkcdABCDEFlmef

623 else: 

624 fac = cast('Callable[[], Any]', self.default_factory) 1opqrstghabniuvwxyzjkcdABCDEFlmef

625 return fac() 1opqrstghabniuvwxyzjkcdABCDEFlmef

626 else: 

627 return None 

628 

629 def is_required(self) -> bool: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

631 

632 Returns: 

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

634 """ 

635 return self.default is PydanticUndefined and self.default_factory is None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

636 

637 def rebuild_annotation(self) -> Any: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

639 

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

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

642 

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

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

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

646 

647 Returns: 

648 The rebuilt annotation. 

649 """ 

650 if not self.metadata: 1opqrstghabniuvwxyzjkcdABCDEFlmef

651 return self.annotation 1opqrstghabniuvwxyzjkcdABCDEFlmef

652 else: 

653 # Annotated arguments must be a tuple 

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

655 

656 def apply_typevars_map( 1opqrstghabuvwxyzjkcdKLMHIJGABCDEFlmef

657 self, 

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

659 globalns: GlobalsNamespace | None = None, 

660 localns: MappingNamespace | None = None, 

661 ) -> None: 

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

663 

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

665 

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

667 

668 Args: 

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

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

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

672 

673 See Also: 

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

675 their concrete types. 

676 """ 

677 annotation, _ = _typing_extra.try_eval_type(self.annotation, globalns, localns) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

678 self.annotation = _generics.replace_types(annotation, typevars_map) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

679 

680 def __repr_args__(self) -> ReprArgs: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

681 yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation)) 1opqrstghabniuvwxyzjkcdABCDEFlmef

682 yield 'required', self.is_required() 1opqrstghabniuvwxyzjkcdABCDEFlmef

683 

684 for s in self.__slots__: 1opqrstghabniuvwxyzjkcdABCDEFlmef

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

686 # By yielding a three-tuple: 

687 if s in ('annotation', '_attributes_set', '_complete', '_original_assignment', '_original_annotation'): 1opqrstghabniuvwxyzjkcdABCDEFlmef

688 continue 1opqrstghabniuvwxyzjkcdABCDEFlmef

689 elif s == 'metadata' and not self.metadata: 1opqrstghabniuvwxyzjkcdABCDEFlmef

690 continue 1opqrstghabniuvwxyzjkcdABCDEFlmef

691 elif s == 'repr' and self.repr is True: 1opqrstghabniuvwxyzjkcdABCDEFlmef

692 continue 1opqrstghabniuvwxyzjkcdABCDEFlmef

693 if s == 'frozen' and self.frozen is False: 1opqrstghabniuvwxyzjkcdABCDEFlmef

694 continue 1opqrstghabniuvwxyzjkcdABCDEFlmef

695 if s == 'validation_alias' and self.validation_alias == self.alias: 1opqrstghabniuvwxyzjkcdABCDEFlmef

696 continue 1opqrstghabniuvwxyzjkcdABCDEFlmef

697 if s == 'serialization_alias' and self.serialization_alias == self.alias: 1opqrstghabniuvwxyzjkcdABCDEFlmef

698 continue 1opqrstghabniuvwxyzjkcdABCDEFlmef

699 if s == 'default' and self.default is not PydanticUndefined: 1opqrstghabniuvwxyzjkcdABCDEFlmef

700 yield 'default', self.default 1opqrstghabniuvwxyzjkcdABCDEFlmef

701 elif s == 'default_factory' and self.default_factory is not None: 1opqrstghabniuvwxyzjkcdABCDEFlmef

702 yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory)) 1opqrstghabniuvwxyzjkcdABCDEFlmef

703 else: 

704 value = getattr(self, s) 1opqrstghabniuvwxyzjkcdABCDEFlmef

705 if value is not None and value is not PydanticUndefined: 1opqrstghabniuvwxyzjkcdABCDEFlmef

706 yield s, value 1opqrstghabniuvwxyzjkcdABCDEFlmef

707 

708 

709class _EmptyKwargs(typing_extensions.TypedDict): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

711 

712 

713_DefaultValues = { 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

714 'default': ..., 

715 'default_factory': None, 

716 'alias': None, 

717 'alias_priority': None, 

718 'validation_alias': None, 

719 'serialization_alias': None, 

720 'title': None, 

721 'description': None, 

722 'examples': None, 

723 'exclude': None, 

724 'discriminator': None, 

725 'json_schema_extra': None, 

726 'frozen': None, 

727 'validate_default': None, 

728 'repr': True, 

729 'init': None, 

730 'init_var': None, 

731 'kw_only': None, 

732 'pattern': None, 

733 'strict': None, 

734 'gt': None, 

735 'ge': None, 

736 'lt': None, 

737 'le': None, 

738 'multiple_of': None, 

739 'allow_inf_nan': None, 

740 'max_digits': None, 

741 'decimal_places': None, 

742 'min_length': None, 

743 'max_length': None, 

744 'coerce_numbers_to_str': None, 

745} 

746 

747 

748_T = TypeVar('_T') 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

749 

750 

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

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

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

754def Field( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

756 *, 

757 alias: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

758 alias_priority: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

759 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

760 serialization_alias: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

761 title: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

762 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

763 description: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

764 examples: list[Any] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

765 exclude: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

766 discriminator: str | types.Discriminator | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

767 deprecated: Deprecated | str | bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

768 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

769 frozen: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

770 validate_default: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

771 repr: bool = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

772 init: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

773 init_var: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

774 kw_only: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

775 pattern: str | typing.Pattern[str] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

776 strict: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

777 coerce_numbers_to_str: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

778 gt: annotated_types.SupportsGt | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

779 ge: annotated_types.SupportsGe | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

780 lt: annotated_types.SupportsLt | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

781 le: annotated_types.SupportsLe | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

782 multiple_of: float | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

783 allow_inf_nan: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

784 max_digits: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

785 decimal_places: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

786 min_length: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

787 max_length: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

788 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

789 fail_fast: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

790 **extra: Unpack[_EmptyKwargs], 1ghabnijkcdHIJGlmef

791) -> Any: ... 1ghabnijkcdHIJGlmef

792@overload # `default` argument set 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

793def Field( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

794 default: _T, 1ghabnijkcdHIJGlmef

795 *, 

796 alias: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

797 alias_priority: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

798 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

799 serialization_alias: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

800 title: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

801 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

802 description: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

803 examples: list[Any] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

804 exclude: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

805 discriminator: str | types.Discriminator | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

806 deprecated: Deprecated | str | bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

807 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

808 frozen: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

809 validate_default: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

810 repr: bool = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

811 init: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

812 init_var: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

813 kw_only: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

814 pattern: str | typing.Pattern[str] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

815 strict: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

816 coerce_numbers_to_str: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

817 gt: annotated_types.SupportsGt | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

818 ge: annotated_types.SupportsGe | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

819 lt: annotated_types.SupportsLt | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

820 le: annotated_types.SupportsLe | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

821 multiple_of: float | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

822 allow_inf_nan: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

823 max_digits: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

824 decimal_places: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

825 min_length: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

826 max_length: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

827 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

828 fail_fast: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

829 **extra: Unpack[_EmptyKwargs], 1ghabnijkcdHIJGlmef

830) -> _T: ... 1ghabnijkcdHIJGlmef

831@overload # `default_factory` argument set 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

832def Field( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

833 *, 

834 default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T], 1ghabnijkcdHIJGlmef

835 alias: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

836 alias_priority: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

837 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

838 serialization_alias: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

839 title: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

840 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

841 description: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

842 examples: list[Any] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

843 exclude: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

844 discriminator: str | types.Discriminator | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

845 deprecated: Deprecated | str | bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

846 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

847 frozen: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

848 validate_default: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

849 repr: bool = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

850 init: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

851 init_var: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

852 kw_only: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

853 pattern: str | typing.Pattern[str] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

854 strict: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

855 coerce_numbers_to_str: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

856 gt: annotated_types.SupportsGt | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

857 ge: annotated_types.SupportsGe | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

858 lt: annotated_types.SupportsLt | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

859 le: annotated_types.SupportsLe | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

860 multiple_of: float | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

861 allow_inf_nan: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

862 max_digits: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

863 decimal_places: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

864 min_length: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

865 max_length: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

866 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

867 fail_fast: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

868 **extra: Unpack[_EmptyKwargs], 1ghabnijkcdHIJGlmef

869) -> _T: ... 1ghabnijkcdHIJGlmef

870@overload 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

871def Field( # No default set 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

872 *, 

873 alias: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

874 alias_priority: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

875 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

876 serialization_alias: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

877 title: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

878 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

879 description: str | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

880 examples: list[Any] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

881 exclude: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

882 discriminator: str | types.Discriminator | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

883 deprecated: Deprecated | str | bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

884 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

885 frozen: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

886 validate_default: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

887 repr: bool = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

888 init: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

889 init_var: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

890 kw_only: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

891 pattern: str | typing.Pattern[str] | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

892 strict: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

893 coerce_numbers_to_str: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

894 gt: annotated_types.SupportsGt | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

895 ge: annotated_types.SupportsGe | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

896 lt: annotated_types.SupportsLt | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

897 le: annotated_types.SupportsLe | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

898 multiple_of: float | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

899 allow_inf_nan: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

900 max_digits: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

901 decimal_places: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

902 min_length: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

903 max_length: int | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

904 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

905 fail_fast: bool | None = _Unset, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

906 **extra: Unpack[_EmptyKwargs], 1ghabnijkcdHIJGlmef

907) -> Any: ... 1ghabnijkcdHIJGlmef

908def Field( # noqa: C901 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

909 default: Any = PydanticUndefined, 

910 *, 

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

912 alias: str | None = _Unset, 

913 alias_priority: int | None = _Unset, 

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

915 serialization_alias: str | None = _Unset, 

916 title: str | None = _Unset, 

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

918 description: str | None = _Unset, 

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

920 exclude: bool | None = _Unset, 

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

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

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

924 frozen: bool | None = _Unset, 

925 validate_default: bool | None = _Unset, 

926 repr: bool = _Unset, 

927 init: bool | None = _Unset, 

928 init_var: bool | None = _Unset, 

929 kw_only: bool | None = _Unset, 

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

931 strict: bool | None = _Unset, 

932 coerce_numbers_to_str: bool | None = _Unset, 

933 gt: annotated_types.SupportsGt | None = _Unset, 

934 ge: annotated_types.SupportsGe | None = _Unset, 

935 lt: annotated_types.SupportsLt | None = _Unset, 

936 le: annotated_types.SupportsLe | None = _Unset, 

937 multiple_of: float | None = _Unset, 

938 allow_inf_nan: bool | None = _Unset, 

939 max_digits: int | None = _Unset, 

940 decimal_places: int | None = _Unset, 

941 min_length: int | None = _Unset, 

942 max_length: int | None = _Unset, 

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

944 fail_fast: bool | None = _Unset, 

945 **extra: Unpack[_EmptyKwargs], 

946) -> Any: 

947 """!!! abstract "Usage Documentation" 

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

949 

950 Create a field for objects that can be configured. 

951 

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

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

954 

955 Note: 

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

957 

958 Args: 

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

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

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

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

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

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

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

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

967 title: Human-readable title. 

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

969 description: Human-readable description. 

970 examples: Example values for this field. 

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

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

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

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

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

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

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

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

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

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

981 (Only applies to dataclasses.) 

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

983 (Only applies to dataclasses.) 

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

985 (Only applies to dataclasses.) 

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

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

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

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

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

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

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

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

994 min_length: Minimum length for iterables. 

995 max_length: Maximum length for iterables. 

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

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

998 max_digits: Maximum number of allow digits for strings. 

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

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

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

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

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

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

1005 

1006 !!! warning Deprecated 

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

1008 

1009 Returns: 

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

1011 type-annotated fields without causing a type error. 

1012 """ 

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

1014 const = extra.pop('const', None) # type: ignore 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1015 if const is not None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1017 

1018 min_items = extra.pop('min_items', None) # type: ignore 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1019 if min_items is not None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1021 if min_length in (None, _Unset): 1opqrstghabniuvwxyzjkcdABCDEFlmef

1022 min_length = min_items # type: ignore 1opqrstghabniuvwxyzjkcdABCDEFlmef

1023 

1024 max_items = extra.pop('max_items', None) # type: ignore 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1025 if max_items is not None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1027 if max_length in (None, _Unset): 1opqrstghabniuvwxyzjkcdABCDEFlmef

1028 max_length = max_items # type: ignore 1opqrstghabniuvwxyzjkcdABCDEFlmef

1029 

1030 unique_items = extra.pop('unique_items', None) # type: ignore 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1031 if unique_items is not None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1032 raise PydanticUserError( 1opqrstghabniuvwxyzjkcdABCDEFlmef

1033 ( 

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

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

1036 ), 

1037 code='removed-kwargs', 

1038 ) 

1039 

1040 allow_mutation = extra.pop('allow_mutation', None) # type: ignore 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1041 if allow_mutation is not None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1043 if allow_mutation is False: 1opqrstghabniuvwxyzjkcdABCDEFlmef

1044 frozen = True 1opqrstghabniuvwxyzjkcdABCDEFlmef

1045 

1046 regex = extra.pop('regex', None) # type: ignore 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1047 if regex is not None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1049 

1050 if extra: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1051 warn( 1opqrstghabniuvwxyzjkcdABCDEFlmef

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

1053 ' Use `json_schema_extra` instead.' 

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

1055 DeprecationWarning, 

1056 ) 

1057 if not json_schema_extra or json_schema_extra is _Unset: 1opqrstghabniuvwxyzjkcdABCDEFlmef

1058 json_schema_extra = extra # type: ignore 1opqrstghabniuvwxyzjkcdABCDEFlmef

1059 

1060 if ( 1opqrstniuvwxyzKLMABCDEF

1061 validation_alias 

1062 and validation_alias is not _Unset 

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

1064 ): 

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

1066 

1067 if serialization_alias in (_Unset, None) and isinstance(alias, str): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1068 serialization_alias = alias 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1069 

1070 if validation_alias in (_Unset, None): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1071 validation_alias = alias 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1072 

1073 include = extra.pop('include', None) # type: ignore 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1074 if include is not None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1076 

1077 return FieldInfo.from_field( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1078 default, 

1079 default_factory=default_factory, 

1080 alias=alias, 

1081 alias_priority=alias_priority, 

1082 validation_alias=validation_alias, 

1083 serialization_alias=serialization_alias, 

1084 title=title, 

1085 field_title_generator=field_title_generator, 

1086 description=description, 

1087 examples=examples, 

1088 exclude=exclude, 

1089 discriminator=discriminator, 

1090 deprecated=deprecated, 

1091 json_schema_extra=json_schema_extra, 

1092 frozen=frozen, 

1093 pattern=pattern, 

1094 validate_default=validate_default, 

1095 repr=repr, 

1096 init=init, 

1097 init_var=init_var, 

1098 kw_only=kw_only, 

1099 coerce_numbers_to_str=coerce_numbers_to_str, 

1100 strict=strict, 

1101 gt=gt, 

1102 ge=ge, 

1103 lt=lt, 

1104 le=le, 

1105 multiple_of=multiple_of, 

1106 min_length=min_length, 

1107 max_length=max_length, 

1108 allow_inf_nan=allow_inf_nan, 

1109 max_digits=max_digits, 

1110 decimal_places=decimal_places, 

1111 union_mode=union_mode, 

1112 fail_fast=fail_fast, 

1113 ) 

1114 

1115 

1116_FIELD_ARG_NAMES = set(inspect.signature(Field).parameters) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1117_FIELD_ARG_NAMES.remove('extra') # do not include the varkwargs parameter 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1118 

1119 

1120class ModelPrivateAttr(_repr.Representation): 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1122 

1123 !!! warning 

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

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

1126 

1127 Attributes: 

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

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

1130 attribute if not provided. 

1131 """ 

1132 

1133 __slots__ = ('default', 'default_factory') 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1134 

1135 def __init__( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1137 ) -> None: 

1138 if default is Ellipsis: 1opqrstghabniuvwxyzjkcdABCDEFlmef

1139 self.default = PydanticUndefined 1opqrstghabniuvwxyzjkcdABCDEFlmef

1140 else: 

1141 self.default = default 1opqrstghabniuvwxyzjkcdABCDEFlmef

1142 self.default_factory = default_factory 1opqrstghabniuvwxyzjkcdABCDEFlmef

1143 

1144 if not typing.TYPE_CHECKING: 1144 ↛ 1156line 1144 didn't jump to line 1156 because the condition on line 1144 was always true1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1146 

1147 def __getattr__(self, item: str) -> Any: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

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

1150 """ 

1151 if item in {'__get__', '__set__', '__delete__'}: 1opqrstghabniuvwxyzjkcdABCDEFlmef

1152 if hasattr(self.default, item): 1opqrstghabniuvwxyzjkcdABCDEFlmef

1153 return getattr(self.default, item) 1opqrstghabniuvwxyzjkcdABCDEFlmef

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

1155 

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

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

1158 default = self.default 1opqrstghabniuvwxyzjkcdABCDEFlmef

1159 if default is PydanticUndefined: 1opqrstghabniuvwxyzjkcdABCDEFlmef

1160 return 1opqrstghabniuvwxyzjkcdABCDEFlmef

1161 set_name = getattr(default, '__set_name__', None) 1opqrstghabniuvwxyzjkcdABCDEFlmef

1162 if callable(set_name): 1opqrstghabniuvwxyzjkcdABCDEFlmef

1163 set_name(cls, name) 1opqrstghabniuvwxyzjkcdABCDEFlmef

1164 

1165 def get_default(self) -> Any: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1167 

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

1169 

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

1171 

1172 Returns: 

1173 The default value of the object. 

1174 """ 

1175 return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() 1opqrstghabniuvwxyzjkcdABCDEFlmef

1176 

1177 def __eq__(self, other: Any) -> bool: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1178 return isinstance(other, self.__class__) and (self.default, self.default_factory) == ( 1opqrstghabniuvwxyzjkcdABCDEFlmef

1179 other.default, 

1180 other.default_factory, 

1181 ) 

1182 

1183 

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

1185# to understand the magic that happens at runtime. 

1186@overload # `default` argument set 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1187def PrivateAttr( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1188 default: _T, 1ghabnijkcdHIJGlmef

1189 *, 

1190 init: Literal[False] = False, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1191) -> _T: ... 1ghabnijkcdHIJGlmef

1192@overload # `default_factory` argument set 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1193def PrivateAttr( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1194 *, 

1195 default_factory: Callable[[], _T], 1ghabnijkcdHIJGlmef

1196 init: Literal[False] = False, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1197) -> _T: ... 1ghabnijkcdHIJGlmef

1198@overload # No default set 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1199def PrivateAttr( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1200 *, 

1201 init: Literal[False] = False, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1202) -> Any: ... 1ghabnijkcdHIJGlmef

1203def PrivateAttr( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1204 default: Any = PydanticUndefined, 

1205 *, 

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

1207 init: Literal[False] = False, 

1208) -> Any: 

1209 """!!! abstract "Usage Documentation" 

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

1211 

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

1213 

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

1215 

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

1217 

1218 Args: 

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

1220 default_factory: Callable that will be 

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

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

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

1224 

1225 Returns: 

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

1227 

1228 Raises: 

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

1230 """ 

1231 if default is not PydanticUndefined and default_factory is not None: 1opqrstghabniuvwxyzjkcdABCDEFlmef

1232 raise TypeError('cannot specify both default and default_factory') 1opqrstghabniuvwxyzjkcdABCDEFlmef

1233 

1234 return ModelPrivateAttr( 1opqrstghabniuvwxyzjkcdABCDEFlmef

1235 default, 

1236 default_factory=default_factory, 

1237 ) 

1238 

1239 

1240@dataclasses.dataclass(**_internal_dataclass.slots_true) 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1241class ComputedFieldInfo: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1243 

1244 Attributes: 

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

1246 wrapped_property: The wrapped computed field property. 

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

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

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

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

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

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

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

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

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

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

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

1258 """ 

1259 

1260 decorator_repr: ClassVar[str] = '@computed_field' 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1261 wrapped_property: property 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1262 return_type: Any 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1263 alias: str | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1264 alias_priority: int | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1265 title: str | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1266 field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1267 description: str | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1268 deprecated: Deprecated | str | bool | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1269 examples: list[Any] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1270 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1271 repr: bool 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1272 

1273 @property 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1274 def deprecation_message(self) -> str | None: 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

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

1276 if self.deprecated is None: 1opqrstghabniuvwxyzjkcdABCDEFlmef

1277 return None 1opqrstghabniuvwxyzjkcdABCDEFlmef

1278 if isinstance(self.deprecated, bool): 1opqrstghabniuvwxyzjkcdABCDEFlmef

1279 return 'deprecated' if self.deprecated else None 1opqrstghabniuvwxyzjkcdABCDEFlmef

1280 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1opqrstghabniuvwxyzjkcdABCDEFlmef

1281 

1282 

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

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

1285 wrapped_name: str = '' 1opqrstghabniuvwxyzjkcdABCDEFlmef

1286 

1287 if isinstance(property_, property): 1opqrstghabniuvwxyzjkcdABCDEFlmef

1288 wrapped_name = getattr(property_.fget, '__name__', '') 1opqrstghabniuvwxyzjkcdABCDEFlmef

1289 elif isinstance(property_, cached_property): # type: ignore 1opqrstghabniuvwxyzjkcdABCDEFlmef

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

1291 

1292 return wrapped_name.startswith('_') and not wrapped_name.startswith('__') 1opqrstghabniuvwxyzjkcdABCDEFlmef

1293 

1294 

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

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

1297PropertyT = typing.TypeVar('PropertyT') 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1298 

1299 

1300@typing.overload 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1301def computed_field(func: PropertyT, /) -> PropertyT: ... 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1302 

1303 

1304@typing.overload 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1305def computed_field( 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1306 *, 

1307 alias: str | None = None, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1308 alias_priority: int | None = None, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1309 title: str | None = None, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1310 field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1311 description: str | None = None, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1312 deprecated: Deprecated | str | bool | None = None, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1313 examples: list[Any] | None = None, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1314 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1315 repr: bool = True, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1316 return_type: Any = PydanticUndefined, 1opqrstghabniuvwxyzjkcdKLMHIJGABCDEFlmef

1317) -> typing.Callable[[PropertyT], PropertyT]: ... 1ghabnijkcdHIJGlmef

1318 

1319 

1320def computed_field( 1opqrstghabuvwxyzjkcdKLMHIJGABCDEFlmef

1321 func: PropertyT | None = None, 

1322 /, 

1323 *, 

1324 alias: str | None = None, 

1325 alias_priority: int | None = None, 

1326 title: str | None = None, 

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

1328 description: str | None = None, 

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

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

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

1332 repr: bool | None = None, 

1333 return_type: Any = PydanticUndefined, 

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

1335 """!!! abstract "Usage Documentation" 

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

1337 

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

1339 

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

1341 

1342 ```python 

1343 from pydantic import BaseModel, computed_field 

1344 

1345 class Rectangle(BaseModel): 

1346 width: int 

1347 length: int 

1348 

1349 @computed_field 

1350 @property 

1351 def area(self) -> int: 

1352 return self.width * self.length 

1353 

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

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

1356 ``` 

1357 

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

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

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

1361 

1362 !!! warning "Mypy Warning" 

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

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

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

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

1367 

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

1369 

1370 ```python 

1371 import random 

1372 

1373 from pydantic import BaseModel, computed_field 

1374 

1375 class Square(BaseModel): 

1376 width: float 

1377 

1378 @computed_field 

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

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

1381 

1382 @area.setter 

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

1384 self.width = new_area**0.5 

1385 

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

1387 def random_number(self) -> int: 

1388 return random.randint(0, 1_000) 

1389 

1390 square = Square(width=1.3) 

1391 

1392 # `random_number` does not appear in representation 

1393 print(repr(square)) 

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

1395 

1396 print(square.random_number) 

1397 #> 3 

1398 

1399 square.area = 4 

1400 

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

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

1403 ``` 

1404 

1405 !!! warning "Overriding with `computed_field`" 

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

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

1408 See the example below: 

1409 

1410 ```python 

1411 from pydantic import BaseModel, computed_field 

1412 

1413 class Parent(BaseModel): 

1414 a: str 

1415 

1416 try: 

1417 

1418 class Child(Parent): 

1419 @computed_field 

1420 @property 

1421 def a(self) -> str: 

1422 return 'new a' 

1423 

1424 except ValueError as e: 

1425 print(repr(e)) 

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

1427 ``` 

1428 

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

1430 

1431 ```python 

1432 from functools import cached_property 

1433 

1434 from pydantic import BaseModel, computed_field 

1435 

1436 class Model(BaseModel): 

1437 foo: int 

1438 

1439 @computed_field 

1440 @cached_property 

1441 def _private_cached_property(self) -> int: 

1442 return -self.foo 

1443 

1444 @computed_field 

1445 @property 

1446 def _private_property(self) -> int: 

1447 return -self.foo 

1448 

1449 m = Model(foo=1) 

1450 print(repr(m)) 

1451 #> Model(foo=1) 

1452 ``` 

1453 

1454 Args: 

1455 func: the function to wrap. 

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

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

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

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

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

1461 docstring 

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

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

1464 `deprecated` decorator. 

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

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

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

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

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

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

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

1472 objects. 

1473 

1474 Returns: 

1475 A proxy wrapper for the property. 

1476 """ 

1477 

1478 def dec(f: Any) -> Any: 1opqrstghabniuvwxyzjkcdABCDEFlmef

1479 nonlocal description, deprecated, return_type, alias_priority 

1480 unwrapped = _decorators.unwrap_wrapped_function(f) 1opqrstghabniuvwxyzjkcdABCDEFlmef

1481 

1482 if description is None and unwrapped.__doc__: 1opqrstghabniuvwxyzjkcdABCDEFlmef

1483 description = inspect.cleandoc(unwrapped.__doc__) 1opqrstghabniuvwxyzjkcdABCDEFlmef

1484 

1485 if deprecated is None and hasattr(unwrapped, '__deprecated__'): 1opqrstghabniuvwxyzjkcdABCDEFlmef

1486 deprecated = unwrapped.__deprecated__ 1opqrstghabniuvwxyzjkcdABCDEFlmef

1487 

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

1489 f = _decorators.ensure_property(f) 1opqrstghabniuvwxyzjkcdABCDEFlmef

1490 alias_priority = (alias_priority or 2) if alias is not None else None 1opqrstghabniuvwxyzjkcdABCDEFlmef

1491 

1492 if repr is None: 1opqrstghabniuvwxyzjkcdABCDEFlmef

1493 repr_: bool = not _wrapped_property_is_private(property_=f) 1opqrstghabniuvwxyzjkcdABCDEFlmef

1494 else: 

1495 repr_ = repr 1opqrstghabniuvwxyzjkcdABCDEFlmef

1496 

1497 dec_info = ComputedFieldInfo( 1opqrstghabniuvwxyzjkcdABCDEFlmef

1498 f, 

1499 return_type, 

1500 alias, 

1501 alias_priority, 

1502 title, 

1503 field_title_generator, 

1504 description, 

1505 deprecated, 

1506 examples, 

1507 json_schema_extra, 

1508 repr_, 

1509 ) 

1510 return _decorators.PydanticDescriptorProxy(f, dec_info) 1opqrstghabniuvwxyzjkcdABCDEFlmef

1511 

1512 if func is None: 1opqrstghabniuvwxyzjkcdABCDEFlmef

1513 return dec 1opqrstghabniuvwxyzjkcdABCDEFlmef

1514 else: 

1515 return dec(func) 1opqrstghabniuvwxyzjkcdABCDEFlmef