Coverage for pydantic/fields.py: 98.60%

465 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-05-02 08:21 +0000

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

2 

3from __future__ import annotations as _annotations 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

4 

5import dataclasses 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

6import inspect 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

7import sys 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

8import typing 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

9from collections.abc import Callable, Mapping 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

10from copy import copy 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

11from dataclasses import Field as DataclassField 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

12from functools import cached_property 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

14from warnings import warn 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

15 

16import annotated_types 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

17import typing_extensions 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

18from pydantic_core import PydanticUndefined 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

19from typing_extensions import TypeAlias, Unpack, deprecated 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

20from typing_inspection import typing_objects 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

22 

23from . import types 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

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

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

27from .config import JsonDict 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

28from .errors import PydanticForbiddenQualifier, PydanticUserError 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

29from .json_schema import PydanticJsonSchemaWarning 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

30from .warnings import PydanticDeprecatedSince20 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

31 

32if typing.TYPE_CHECKING: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

33 from ._internal._config import ConfigWrapper 

34 from ._internal._repr import ReprArgs 1l

35else: 

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

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

38 DeprecationWarning = PydanticDeprecatedSince20 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

39 

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

41 

42 

43_Unset: Any = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

44 

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

46 import warnings 1abcdefJghi

47 

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

49else: 

50 Deprecated: TypeAlias = deprecated 1rstuvwjkqlxyzABCmnNOPKLMDEFGHIop

51 

52 

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

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

55 

56 # TODO PEP 747: use TypeForm: 

57 annotation: type[Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

59 alias: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

60 alias_priority: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

62 serialization_alias: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

63 title: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

65 description: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

66 examples: list[Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

67 exclude: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

68 gt: annotated_types.SupportsGt | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

69 ge: annotated_types.SupportsGe | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

70 lt: annotated_types.SupportsLt | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

71 le: annotated_types.SupportsLe | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

72 multiple_of: float | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

73 strict: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

74 min_length: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

75 max_length: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

77 allow_inf_nan: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

78 max_digits: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

79 decimal_places: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

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

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

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

84 frozen: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

85 validate_default: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

86 repr: bool 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

87 init: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

88 init_var: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

89 kw_only: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

90 coerce_numbers_to_str: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

91 fail_fast: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

92 

93 

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

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

96 

97 default: Any 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

98 

99 

100class FieldInfo(_repr.Representation): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

102 

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

104 function is explicitly used. 

105 

106 !!! warning 

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

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

109 

110 Attributes: 

111 annotation: The type annotation of the field. 

112 default: The default value of the field. 

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

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

115 alias: The alias name of the field. 

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

117 validation_alias: The validation alias of the field. 

118 serialization_alias: The serialization alias of the field. 

119 title: The title of the field. 

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

121 description: The description of the field. 

122 examples: List of examples of the field. 

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

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

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

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

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

128 frozen: Whether the field is frozen. 

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

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

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

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

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

134 metadata: List of metadata constraints. 

135 """ 

136 

137 annotation: type[Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

138 default: Any 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

139 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

140 alias: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

141 alias_priority: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

142 validation_alias: str | AliasPath | AliasChoices | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

143 serialization_alias: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

144 title: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

145 field_title_generator: Callable[[str, FieldInfo], str] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

146 description: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

147 examples: list[Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

148 exclude: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

149 discriminator: str | types.Discriminator | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

150 deprecated: Deprecated | str | bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

151 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

152 frozen: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

153 validate_default: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

154 repr: bool 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

155 init: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

156 init_var: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

157 kw_only: bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

158 metadata: list[Any] 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

159 

160 __slots__ = ( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

161 'annotation', 

162 'default', 

163 'default_factory', 

164 'alias', 

165 'alias_priority', 

166 'validation_alias', 

167 'serialization_alias', 

168 'title', 

169 'field_title_generator', 

170 'description', 

171 'examples', 

172 'exclude', 

173 'discriminator', 

174 'deprecated', 

175 'json_schema_extra', 

176 'frozen', 

177 'validate_default', 

178 'repr', 

179 'init', 

180 'init_var', 

181 'kw_only', 

182 'metadata', 

183 '_attributes_set', 

184 '_qualifiers', 

185 '_complete', 

186 '_original_assignment', 

187 '_original_annotation', 

188 ) 

189 

190 # used to convert kwargs to metadata/constraints, 

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

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

193 'strict': types.Strict, 

194 'gt': annotated_types.Gt, 

195 'ge': annotated_types.Ge, 

196 'lt': annotated_types.Lt, 

197 'le': annotated_types.Le, 

198 'multiple_of': annotated_types.MultipleOf, 

199 'min_length': annotated_types.MinLen, 

200 'max_length': annotated_types.MaxLen, 

201 'pattern': None, 

202 'allow_inf_nan': None, 

203 'max_digits': None, 

204 'decimal_places': None, 

205 'union_mode': None, 

206 'coerce_numbers_to_str': None, 

207 'fail_fast': types.FailFast, 

208 } 

209 

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

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

212 or one of the constructor classmethods. 

213 

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

215 """ 

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

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

218 self.annotation = kwargs.get('annotation') 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

219 

220 default = kwargs.pop('default', PydanticUndefined) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

221 if default is Ellipsis: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

222 self.default = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

223 self._attributes_set.pop('default', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

224 else: 

225 self.default = default 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

226 

227 self.default_factory = kwargs.pop('default_factory', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

228 

229 if self.default is not PydanticUndefined and self.default_factory is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

230 raise TypeError('cannot specify both default and default_factory') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

231 

232 self.alias = kwargs.pop('alias', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

233 self.validation_alias = kwargs.pop('validation_alias', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

234 self.serialization_alias = kwargs.pop('serialization_alias', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

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

237 self.title = kwargs.pop('title', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

238 self.field_title_generator = kwargs.pop('field_title_generator', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

239 self.description = kwargs.pop('description', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

240 self.examples = kwargs.pop('examples', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

241 self.exclude = kwargs.pop('exclude', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

242 self.discriminator = kwargs.pop('discriminator', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

244 self.deprecated = kwargs.pop('deprecated', getattr(self, 'deprecated', None)) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

245 self.repr = kwargs.pop('repr', True) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

246 self.json_schema_extra = kwargs.pop('json_schema_extra', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

247 self.validate_default = kwargs.pop('validate_default', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

248 self.frozen = kwargs.pop('frozen', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

249 # currently only used on dataclasses 

250 self.init = kwargs.pop('init', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

251 self.init_var = kwargs.pop('init_var', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

252 self.kw_only = kwargs.pop('kw_only', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

253 

254 self.metadata = self._collect_metadata(kwargs) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

255 

256 # Private attributes: 

257 self._qualifiers: set[Qualifier] = set() 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

258 # Used to rebuild FieldInfo instances: 

259 self._complete = True 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

260 self._original_annotation: Any = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

261 self._original_assignment: Any = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

262 

263 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

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

266 

267 Args: 

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

269 **kwargs: Additional arguments dictionary. 

270 

271 Raises: 

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

273 

274 Returns: 

275 A new FieldInfo object with the given parameters. 

276 

277 Example: 

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

279 

280 ```python 

281 import pydantic 

282 

283 class MyModel(pydantic.BaseModel): 

284 foo: int = pydantic.Field(4) 

285 ``` 

286 """ 

287 if 'annotation' in kwargs: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

289 return FieldInfo(default=default, **kwargs) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

290 

291 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

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

294 

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

296 

297 ```python 

298 import pydantic 

299 

300 class MyModel(pydantic.BaseModel): 

301 foo: int # <-- like this 

302 ``` 

303 

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

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

306 

307 ```python 

308 from typing import Annotated 

309 

310 import annotated_types 

311 

312 import pydantic 

313 

314 class MyModel(pydantic.BaseModel): 

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

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

317 ``` 

318 

319 Args: 

320 annotation: An annotation object. 

321 

322 Returns: 

323 An instance of the field metadata. 

324 """ 

325 try: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

326 inspected_ann = inspect_annotation( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

327 annotation, 

328 annotation_source=_source, 

329 unpack_type_aliases='skip', 

330 ) 

331 except ForbiddenQualifier as e: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

332 raise PydanticForbiddenQualifier(e.qualifier, annotation) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

333 

334 # TODO check for classvar and error? 

335 

336 # No assigned value, this happens when using a bare `Final` qualifier (also for other 

337 # qualifiers, but they shouldn't appear here). In this case we infer the type as `Any` 

338 # because we don't have any assigned value. 

339 type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

340 final = 'final' in inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

341 metadata = inspected_ann.metadata 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

342 

343 if not metadata: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

344 # No metadata, e.g. `field: int`, or `field: Final[str]`: 

345 field_info = FieldInfo(annotation=type_expr, frozen=final or None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

346 field_info._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

347 return field_info 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

348 

349 # With metadata, e.g. `field: Annotated[int, Field(...), Gt(1)]`: 

350 field_info_annotations = [a for a in metadata if isinstance(a, FieldInfo)] 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

351 field_info = FieldInfo.merge_field_infos(*field_info_annotations, annotation=type_expr) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

352 

353 new_field_info = copy(field_info) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

354 new_field_info.annotation = type_expr 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

355 new_field_info.frozen = final or field_info.frozen 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

356 field_metadata: list[Any] = [] 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

357 for a in metadata: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

358 if typing_objects.is_deprecated(a): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

359 new_field_info.deprecated = a.message 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

360 elif not isinstance(a, FieldInfo): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

361 field_metadata.append(a) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

362 else: 

363 field_metadata.extend(a.metadata) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

364 new_field_info.metadata = field_metadata 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

365 new_field_info._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

366 return new_field_info 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

367 

368 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

369 def from_annotated_attribute( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

371 ) -> FieldInfo: 

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

373 

374 This is used in cases like the following: 

375 

376 ```python 

377 from typing import Annotated 

378 

379 import annotated_types 

380 

381 import pydantic 

382 

383 class MyModel(pydantic.BaseModel): 

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

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

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

387 ``` 

388 

389 Args: 

390 annotation: The type annotation of the field. 

391 default: The default value of the field. 

392 

393 Returns: 

394 A field object with the passed values. 

395 """ 

396 if annotation is default: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

397 raise PydanticUserError( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

398 'Error when building FieldInfo from annotated attribute. ' 

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

400 code='unevaluable-type-annotation', 

401 ) 

402 

403 try: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

404 inspected_ann = inspect_annotation( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

405 annotation, 

406 annotation_source=_source, 

407 unpack_type_aliases='skip', 

408 ) 

409 except ForbiddenQualifier as e: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

410 raise PydanticForbiddenQualifier(e.qualifier, annotation) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

411 

412 # TODO check for classvar and error? 

413 

414 # TODO infer from the default, this can be done in v3 once we treat final fields with 

415 # a default as proper fields and not class variables: 

416 type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

417 final = 'final' in inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

418 metadata = inspected_ann.metadata 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

419 

420 if isinstance(default, FieldInfo): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

421 # e.g. `field: int = Field(...)` 

422 default.annotation = type_expr 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

423 default.metadata += metadata 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

424 merged_default = FieldInfo.merge_field_infos( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

425 *[x for x in metadata if isinstance(x, FieldInfo)], 

426 default, 

427 annotation=default.annotation, 

428 ) 

429 merged_default.frozen = final or merged_default.frozen 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

430 merged_default._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

431 return merged_default 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

432 

433 if isinstance(default, dataclasses.Field): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

434 # `collect_dataclass_fields()` passes the dataclass Field as a default. 

435 pydantic_field = FieldInfo._from_dataclass_field(default) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

436 pydantic_field.annotation = type_expr 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

437 pydantic_field.metadata += metadata 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

438 pydantic_field = FieldInfo.merge_field_infos( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

439 *[x for x in metadata if isinstance(x, FieldInfo)], 

440 pydantic_field, 

441 annotation=pydantic_field.annotation, 

442 ) 

443 pydantic_field.frozen = final or pydantic_field.frozen 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

444 pydantic_field.init_var = 'init_var' in inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

445 pydantic_field.init = getattr(default, 'init', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

446 pydantic_field.kw_only = getattr(default, 'kw_only', None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

447 pydantic_field._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

448 return pydantic_field 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

449 

450 if not metadata: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

451 # No metadata, e.g. `field: int = ...`, or `field: Final[str] = ...`: 

452 field_info = FieldInfo(annotation=type_expr, default=default, frozen=final or None) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

453 field_info._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

454 return field_info 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

455 

456 # With metadata, e.g. `field: Annotated[int, Field(...), Gt(1)] = ...`: 

457 field_infos = [a for a in metadata if isinstance(a, FieldInfo)] 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

458 field_info = FieldInfo.merge_field_infos(*field_infos, annotation=type_expr, default=default) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

459 field_metadata: list[Any] = [] 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

460 for a in metadata: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

461 if typing_objects.is_deprecated(a): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

462 field_info.deprecated = a.message 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

463 elif not isinstance(a, FieldInfo): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

464 field_metadata.append(a) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

465 else: 

466 field_metadata.extend(a.metadata) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

467 field_info.metadata = field_metadata 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

468 field_info._qualifiers = inspected_ann.qualifiers 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

469 return field_info 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

470 

471 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

472 def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

474 

475 Later `FieldInfo` instances override earlier ones. 

476 

477 Returns: 

478 FieldInfo: A merged FieldInfo instance. 

479 """ 

480 if len(field_infos) == 1: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

482 field_info = copy(field_infos[0]) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

483 field_info._attributes_set.update(overrides) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

484 

485 default_override = overrides.pop('default', PydanticUndefined) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

486 if default_override is Ellipsis: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

487 default_override = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

488 if default_override is not PydanticUndefined: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

489 field_info.default = default_override 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

490 

491 for k, v in overrides.items(): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

492 setattr(field_info, k, v) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

493 return field_info # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

494 

495 merged_field_info_kwargs: dict[str, Any] = {} 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

496 metadata = {} 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

497 for field_info in field_infos: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

498 attributes_set = field_info._attributes_set.copy() 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

499 

500 try: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

501 json_schema_extra = attributes_set.pop('json_schema_extra') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

502 existing_json_schema_extra = merged_field_info_kwargs.get('json_schema_extra') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

503 

504 if existing_json_schema_extra is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

505 merged_field_info_kwargs['json_schema_extra'] = json_schema_extra 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

506 if isinstance(existing_json_schema_extra, dict): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

507 if isinstance(json_schema_extra, dict): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

508 merged_field_info_kwargs['json_schema_extra'] = { 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

509 **existing_json_schema_extra, 

510 **json_schema_extra, 

511 } 

512 if callable(json_schema_extra): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

513 warn( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

514 'Composing `dict` and `callable` type `json_schema_extra` is not supported.' 

515 'The `callable` type is being ignored.' 

516 "If you'd like support for this behavior, please open an issue on pydantic.", 

517 PydanticJsonSchemaWarning, 

518 ) 

519 elif callable(json_schema_extra): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

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

521 merged_field_info_kwargs['json_schema_extra'] = json_schema_extra 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

522 except KeyError: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

523 pass 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

524 

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

526 merged_field_info_kwargs.update(attributes_set) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

527 

528 for x in field_info.metadata: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

529 if not isinstance(x, FieldInfo): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

530 metadata[type(x)] = x 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

531 

532 merged_field_info_kwargs.update(overrides) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

533 field_info = FieldInfo(**merged_field_info_kwargs) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

534 field_info.metadata = list(metadata.values()) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

535 return field_info 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

536 

537 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

538 def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

540 

541 Args: 

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

543 

544 Returns: 

545 The corresponding `FieldInfo` instance. 

546 

547 Raises: 

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

549 """ 

550 default = dc_field.default 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

551 if default is dataclasses.MISSING: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

552 default = _Unset 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

553 

554 if dc_field.default_factory is dataclasses.MISSING: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

555 default_factory = _Unset 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

556 else: 

557 default_factory = dc_field.default_factory 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

558 

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

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

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

562 

563 @staticmethod 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

565 """Collect annotations from kwargs. 

566 

567 Args: 

568 kwargs: Keyword arguments passed to the function. 

569 

570 Returns: 

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

572 `PydanticMetadata`. 

573 """ 

574 metadata: list[Any] = [] 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

575 general_metadata = {} 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

576 for key, value in list(kwargs.items()): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

577 try: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

578 marker = FieldInfo.metadata_lookup[key] 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

579 except KeyError: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

580 continue 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

581 

582 del kwargs[key] 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

583 if value is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

584 if marker is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

585 general_metadata[key] = value 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

586 else: 

587 metadata.append(marker(value)) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

588 if general_metadata: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

589 metadata.append(_fields.pydantic_general_metadata(**general_metadata)) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

590 return metadata 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

591 

592 @property 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

593 def deprecation_message(self) -> str | None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

595 if self.deprecated is None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

596 return None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

597 if isinstance(self.deprecated, bool): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

598 return 'deprecated' if self.deprecated else None 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

599 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

600 

601 @property 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

602 def default_factory_takes_validated_data(self) -> bool | None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

604 

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

606 """ 

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

608 return _fields.takes_validated_data_argument(self.default_factory) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

609 

610 @overload 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

611 def get_default( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

613 ) -> Any: ... 1jkabcqlmndefKLMJopghi

614 

615 @overload 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

617 

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

619 """Get the default value. 

620 

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

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

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

624 

625 Args: 

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

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

628 

629 Returns: 

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

631 """ 

632 if self.default_factory is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

633 return _utils.smart_deepcopy(self.default) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

634 elif call_default_factory: 634 ↛ 646line 634 didn't jump to line 646 because the condition on line 634 was always true1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

635 if self.default_factory_takes_validated_data: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

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

637 if validated_data is None: 637 ↛ 638line 637 didn't jump to line 638 because the condition on line 637 was never true1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

638 raise ValueError( 

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

640 ) 

641 return fac(validated_data) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

642 else: 

643 fac = cast('Callable[[], Any]', self.default_factory) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

644 return fac() 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

645 else: 

646 return None 

647 

648 def is_required(self) -> bool: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

650 

651 Returns: 

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

653 """ 

654 return self.default is PydanticUndefined and self.default_factory is None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

655 

656 def rebuild_annotation(self) -> Any: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

658 

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

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

661 

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

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

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

665 

666 Returns: 

667 The rebuilt annotation. 

668 """ 

669 if not self.metadata: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

670 return self.annotation 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

671 else: 

672 # Annotated arguments must be a tuple 

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

674 

675 def apply_typevars_map( 1rstuvwjkabcxyzABCmndefNOPKLMJDEFGHIopghi

676 self, 

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

678 globalns: GlobalsNamespace | None = None, 

679 localns: MappingNamespace | None = None, 

680 ) -> None: 

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

682 

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

684 

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

686 

687 Args: 

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

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

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

691 

692 See Also: 

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

694 their concrete types. 

695 """ 

696 annotation, _ = _typing_extra.try_eval_type(self.annotation, globalns, localns) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

697 self.annotation = _generics.replace_types(annotation, typevars_map) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

698 

699 def __repr_args__(self) -> ReprArgs: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

700 yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation)) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

701 yield 'required', self.is_required() 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

702 

703 for s in self.__slots__: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

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

705 # By yielding a three-tuple: 

706 if s in ( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

707 'annotation', 

708 '_attributes_set', 

709 '_qualifiers', 

710 '_complete', 

711 '_original_assignment', 

712 '_original_annotation', 

713 ): 

714 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

715 elif s == 'metadata' and not self.metadata: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

716 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

717 elif s == 'repr' and self.repr is True: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

718 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

719 if s == 'frozen' and self.frozen is False: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

720 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

721 if s == 'validation_alias' and self.validation_alias == self.alias: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

722 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

723 if s == 'serialization_alias' and self.serialization_alias == self.alias: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

724 continue 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

725 if s == 'default' and self.default is not PydanticUndefined: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

726 yield 'default', self.default 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

727 elif s == 'default_factory' and self.default_factory is not None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

728 yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory)) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

729 else: 

730 value = getattr(self, s) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

731 if value is not None and value is not PydanticUndefined: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

732 yield s, value 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

733 

734 

735class _EmptyKwargs(typing_extensions.TypedDict): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

737 

738 

739_DefaultValues = { 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

740 'default': ..., 

741 'default_factory': None, 

742 'alias': None, 

743 'alias_priority': None, 

744 'validation_alias': None, 

745 'serialization_alias': None, 

746 'title': None, 

747 'description': None, 

748 'examples': None, 

749 'exclude': None, 

750 'discriminator': None, 

751 'json_schema_extra': None, 

752 'frozen': None, 

753 'validate_default': None, 

754 'repr': True, 

755 'init': None, 

756 'init_var': None, 

757 'kw_only': None, 

758 'pattern': None, 

759 'strict': None, 

760 'gt': None, 

761 'ge': None, 

762 'lt': None, 

763 'le': None, 

764 'multiple_of': None, 

765 'allow_inf_nan': None, 

766 'max_digits': None, 

767 'decimal_places': None, 

768 'min_length': None, 

769 'max_length': None, 

770 'coerce_numbers_to_str': None, 

771} 

772 

773 

774_T = TypeVar('_T') 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

775 

776 

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

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

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

780def Field( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

782 *, 

783 alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

784 alias_priority: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

785 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

786 serialization_alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

787 title: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

788 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

789 description: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

790 examples: list[Any] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

791 exclude: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

792 discriminator: str | types.Discriminator | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

793 deprecated: Deprecated | str | bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

794 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

795 frozen: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

796 validate_default: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

797 repr: bool = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

798 init: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

799 init_var: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

800 kw_only: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

801 pattern: str | typing.Pattern[str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

802 strict: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

803 coerce_numbers_to_str: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

804 gt: annotated_types.SupportsGt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

805 ge: annotated_types.SupportsGe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

806 lt: annotated_types.SupportsLt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

807 le: annotated_types.SupportsLe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

808 multiple_of: float | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

809 allow_inf_nan: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

810 max_digits: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

811 decimal_places: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

812 min_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

813 max_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

814 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

815 fail_fast: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

816 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefKLMJopghi

817) -> Any: ... 1jkabcqlmndefKLMJopghi

818@overload # `default` argument set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

819def Field( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

820 default: _T, 1jkabcqlmndefKLMJopghi

821 *, 

822 alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

823 alias_priority: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

824 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

825 serialization_alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

826 title: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

827 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

828 description: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

829 examples: list[Any] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

830 exclude: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

831 discriminator: str | types.Discriminator | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

832 deprecated: Deprecated | str | bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

833 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

834 frozen: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

835 validate_default: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

836 repr: bool = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

837 init: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

838 init_var: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

839 kw_only: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

840 pattern: str | typing.Pattern[str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

841 strict: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

842 coerce_numbers_to_str: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

843 gt: annotated_types.SupportsGt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

844 ge: annotated_types.SupportsGe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

845 lt: annotated_types.SupportsLt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

846 le: annotated_types.SupportsLe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

847 multiple_of: float | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

848 allow_inf_nan: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

849 max_digits: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

850 decimal_places: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

851 min_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

852 max_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

853 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

854 fail_fast: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

855 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefKLMJopghi

856) -> _T: ... 1jkabcqlmndefKLMJopghi

857@overload # `default_factory` argument set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

858def Field( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

859 *, 

860 default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T], 1jkabcqlmndefKLMJopghi

861 alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

862 alias_priority: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

863 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

864 serialization_alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

865 title: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

866 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

867 description: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

868 examples: list[Any] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

869 exclude: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

870 discriminator: str | types.Discriminator | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

871 deprecated: Deprecated | str | bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

872 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

873 frozen: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

874 validate_default: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

875 repr: bool = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

876 init: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

877 init_var: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

878 kw_only: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

879 pattern: str | typing.Pattern[str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

880 strict: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

881 coerce_numbers_to_str: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

882 gt: annotated_types.SupportsGt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

883 ge: annotated_types.SupportsGe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

884 lt: annotated_types.SupportsLt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

885 le: annotated_types.SupportsLe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

886 multiple_of: float | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

887 allow_inf_nan: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

888 max_digits: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

889 decimal_places: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

890 min_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

891 max_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

892 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

893 fail_fast: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

894 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefKLMJopghi

895) -> _T: ... 1jkabcqlmndefKLMJopghi

896@overload 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

897def Field( # No default set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

898 *, 

899 alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

900 alias_priority: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

901 validation_alias: str | AliasPath | AliasChoices | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

902 serialization_alias: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

903 title: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

904 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

905 description: str | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

906 examples: list[Any] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

907 exclude: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

908 discriminator: str | types.Discriminator | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

909 deprecated: Deprecated | str | bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

910 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

911 frozen: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

912 validate_default: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

913 repr: bool = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

914 init: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

915 init_var: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

916 kw_only: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

917 pattern: str | typing.Pattern[str] | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

918 strict: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

919 coerce_numbers_to_str: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

920 gt: annotated_types.SupportsGt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

921 ge: annotated_types.SupportsGe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

922 lt: annotated_types.SupportsLt | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

923 le: annotated_types.SupportsLe | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

924 multiple_of: float | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

925 allow_inf_nan: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

926 max_digits: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

927 decimal_places: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

928 min_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

929 max_length: int | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

930 union_mode: Literal['smart', 'left_to_right'] = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

931 fail_fast: bool | None = _Unset, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

932 **extra: Unpack[_EmptyKwargs], 1jkabcqlmndefKLMJopghi

933) -> Any: ... 1jkabcqlmndefKLMJopghi

934def Field( # noqa: C901 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

935 default: Any = PydanticUndefined, 

936 *, 

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

938 alias: str | None = _Unset, 

939 alias_priority: int | None = _Unset, 

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

941 serialization_alias: str | None = _Unset, 

942 title: str | None = _Unset, 

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

944 description: str | None = _Unset, 

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

946 exclude: bool | None = _Unset, 

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

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

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

950 frozen: bool | None = _Unset, 

951 validate_default: bool | None = _Unset, 

952 repr: bool = _Unset, 

953 init: bool | None = _Unset, 

954 init_var: bool | None = _Unset, 

955 kw_only: bool | None = _Unset, 

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

957 strict: bool | None = _Unset, 

958 coerce_numbers_to_str: bool | None = _Unset, 

959 gt: annotated_types.SupportsGt | None = _Unset, 

960 ge: annotated_types.SupportsGe | None = _Unset, 

961 lt: annotated_types.SupportsLt | None = _Unset, 

962 le: annotated_types.SupportsLe | None = _Unset, 

963 multiple_of: float | None = _Unset, 

964 allow_inf_nan: bool | None = _Unset, 

965 max_digits: int | None = _Unset, 

966 decimal_places: int | None = _Unset, 

967 min_length: int | None = _Unset, 

968 max_length: int | None = _Unset, 

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

970 fail_fast: bool | None = _Unset, 

971 **extra: Unpack[_EmptyKwargs], 

972) -> Any: 

973 """!!! abstract "Usage Documentation" 

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

975 

976 Create a field for objects that can be configured. 

977 

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

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

980 

981 Note: 

982 - Any `_Unset` objects will be replaced by the corresponding value defined in the `_DefaultValues` dictionary. If a key for the `_Unset` object is not found in the `_DefaultValues` dictionary, it will default to `None` 

983 

984 Args: 

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

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

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

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

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

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

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

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

993 title: Human-readable title. 

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

995 description: Human-readable description. 

996 examples: Example values for this field. 

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

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

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

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

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

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

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

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

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

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

1007 (Only applies to dataclasses.) 

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

1009 (Only applies to dataclasses.) 

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

1011 (Only applies to dataclasses.) 

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

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

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

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

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

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

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

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

1020 min_length: Minimum length for iterables. 

1021 max_length: Maximum length for iterables. 

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

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

1024 max_digits: Maximum number of allow digits for strings. 

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

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

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

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

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

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

1031 

1032 !!! warning Deprecated 

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

1034 

1035 Returns: 

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

1037 type-annotated fields without causing a type error. 

1038 """ 

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

1040 const = extra.pop('const', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1041 if const is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1043 

1044 min_items = extra.pop('min_items', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1045 if min_items is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1047 if min_length in (None, _Unset): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1048 min_length = min_items # type: ignore 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1049 

1050 max_items = extra.pop('max_items', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1051 if max_items is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1053 if max_length in (None, _Unset): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1054 max_length = max_items # type: ignore 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1055 

1056 unique_items = extra.pop('unique_items', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1057 if unique_items is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1058 raise PydanticUserError( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1059 ( 

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

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

1062 ), 

1063 code='removed-kwargs', 

1064 ) 

1065 

1066 allow_mutation = extra.pop('allow_mutation', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1067 if allow_mutation is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1069 if allow_mutation is False: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1070 frozen = True 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1071 

1072 regex = extra.pop('regex', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1073 if regex is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1075 

1076 if extra: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1077 warn( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

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

1079 ' Use `json_schema_extra` instead.' 

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

1081 DeprecationWarning, 

1082 ) 

1083 if not json_schema_extra or json_schema_extra is _Unset: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1084 json_schema_extra = extra # type: ignore 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1085 

1086 if ( 1rstuvwqlxyzABCNOPDEFGHI

1087 validation_alias 

1088 and validation_alias is not _Unset 

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

1090 ): 

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

1092 

1093 if serialization_alias in (_Unset, None) and isinstance(alias, str): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1094 serialization_alias = alias 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1095 

1096 if validation_alias in (_Unset, None): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1097 validation_alias = alias 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1098 

1099 include = extra.pop('include', None) # type: ignore 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1100 if include is not None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1102 

1103 return FieldInfo.from_field( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1104 default, 

1105 default_factory=default_factory, 

1106 alias=alias, 

1107 alias_priority=alias_priority, 

1108 validation_alias=validation_alias, 

1109 serialization_alias=serialization_alias, 

1110 title=title, 

1111 field_title_generator=field_title_generator, 

1112 description=description, 

1113 examples=examples, 

1114 exclude=exclude, 

1115 discriminator=discriminator, 

1116 deprecated=deprecated, 

1117 json_schema_extra=json_schema_extra, 

1118 frozen=frozen, 

1119 pattern=pattern, 

1120 validate_default=validate_default, 

1121 repr=repr, 

1122 init=init, 

1123 init_var=init_var, 

1124 kw_only=kw_only, 

1125 coerce_numbers_to_str=coerce_numbers_to_str, 

1126 strict=strict, 

1127 gt=gt, 

1128 ge=ge, 

1129 lt=lt, 

1130 le=le, 

1131 multiple_of=multiple_of, 

1132 min_length=min_length, 

1133 max_length=max_length, 

1134 allow_inf_nan=allow_inf_nan, 

1135 max_digits=max_digits, 

1136 decimal_places=decimal_places, 

1137 union_mode=union_mode, 

1138 fail_fast=fail_fast, 

1139 ) 

1140 

1141 

1142_FIELD_ARG_NAMES = set(inspect.signature(Field).parameters) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1143_FIELD_ARG_NAMES.remove('extra') # do not include the varkwargs parameter 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1144 

1145 

1146class ModelPrivateAttr(_repr.Representation): 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1148 

1149 !!! warning 

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

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

1152 

1153 Attributes: 

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

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

1156 attribute if not provided. 

1157 """ 

1158 

1159 __slots__ = ('default', 'default_factory') 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1160 

1161 def __init__( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1163 ) -> None: 

1164 if default is Ellipsis: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1165 self.default = PydanticUndefined 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1166 else: 

1167 self.default = default 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1168 self.default_factory = default_factory 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1169 

1170 if not typing.TYPE_CHECKING: 1170 ↛ 1182line 1170 didn't jump to line 1182 because the condition on line 1170 was always true1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1172 

1173 def __getattr__(self, item: str) -> Any: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

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

1176 """ 

1177 if item in {'__get__', '__set__', '__delete__'}: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1178 if hasattr(self.default, item): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1179 return getattr(self.default, item) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

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

1181 

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

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

1184 default = self.default 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1185 if default is PydanticUndefined: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1186 return 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1187 set_name = getattr(default, '__set_name__', None) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1188 if callable(set_name): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1189 set_name(cls, name) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1190 

1191 def get_default(self) -> Any: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1193 

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

1195 

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

1197 

1198 Returns: 

1199 The default value of the object. 

1200 """ 

1201 return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1202 

1203 def __eq__(self, other: Any) -> bool: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1204 return isinstance(other, self.__class__) and (self.default, self.default_factory) == ( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1205 other.default, 

1206 other.default_factory, 

1207 ) 

1208 

1209 

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

1211# to understand the magic that happens at runtime. 

1212@overload # `default` argument set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1213def PrivateAttr( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1214 default: _T, 1jkabcqlmndefKLMJopghi

1215 *, 

1216 init: Literal[False] = False, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1217) -> _T: ... 1jkabcqlmndefKLMJopghi

1218@overload # `default_factory` argument set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1219def PrivateAttr( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1220 *, 

1221 default_factory: Callable[[], _T], 1jkabcqlmndefKLMJopghi

1222 init: Literal[False] = False, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1223) -> _T: ... 1jkabcqlmndefKLMJopghi

1224@overload # No default set 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1225def PrivateAttr( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1226 *, 

1227 init: Literal[False] = False, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1228) -> Any: ... 1jkabcqlmndefKLMJopghi

1229def PrivateAttr( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1230 default: Any = PydanticUndefined, 

1231 *, 

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

1233 init: Literal[False] = False, 

1234) -> Any: 

1235 """!!! abstract "Usage Documentation" 

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

1237 

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

1239 

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

1241 

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

1243 

1244 Args: 

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

1246 default_factory: Callable that will be 

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

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

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

1250 

1251 Returns: 

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

1253 

1254 Raises: 

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

1256 """ 

1257 if default is not PydanticUndefined and default_factory is not None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1258 raise TypeError('cannot specify both default and default_factory') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1259 

1260 return ModelPrivateAttr( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1261 default, 

1262 default_factory=default_factory, 

1263 ) 

1264 

1265 

1266@dataclasses.dataclass(**_internal_dataclass.slots_true) 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1267class ComputedFieldInfo: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1269 

1270 Attributes: 

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

1272 wrapped_property: The wrapped computed field property. 

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

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

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

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

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

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

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

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

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

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

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

1284 """ 

1285 

1286 decorator_repr: ClassVar[str] = '@computed_field' 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1287 wrapped_property: property 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1288 return_type: Any 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1289 alias: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1290 alias_priority: int | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1291 title: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1292 field_title_generator: Callable[[str, ComputedFieldInfo], str] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1293 description: str | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1294 deprecated: Deprecated | str | bool | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1295 examples: list[Any] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1296 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1297 repr: bool 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1298 

1299 @property 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1300 def deprecation_message(self) -> str | None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1302 if self.deprecated is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1303 return None 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1304 if isinstance(self.deprecated, bool): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1305 return 'deprecated' if self.deprecated else None 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1306 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1307 

1308 def _update_from_config(self, config_wrapper: ConfigWrapper, name: str) -> None: 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

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

1310 title_generator = self.field_title_generator or config_wrapper.field_title_generator 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1311 if title_generator is not None and self.title is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1312 self.title = title_generator(name, self) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1313 if config_wrapper.alias_generator is not None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1314 self._apply_alias_generator(config_wrapper.alias_generator, name) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1315 

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

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

1318 

1319 Args: 

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

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

1322 """ 

1323 # Apply an alias_generator if 

1324 # 1. An alias is not specified 

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

1326 

1327 if self.alias_priority is None or self.alias_priority <= 1 or self.alias is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1328 alias, _, serialization_alias = None, None, None 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1329 

1330 if isinstance(alias_generator, AliasGenerator): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1331 alias, _, serialization_alias = alias_generator.generate_aliases(name) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1332 elif callable(alias_generator): 1332 ↛ 1338line 1332 didn't jump to line 1338 because the condition on line 1332 was always true1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1333 alias = alias_generator(name) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1334 

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

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

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

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

1339 self.alias_priority = 1 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1340 

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

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

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

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

1345 self.alias = _utils.get_first_not_none(serialization_alias, alias) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1346 

1347 

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

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

1350 wrapped_name: str = '' 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1351 

1352 if isinstance(property_, property): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1353 wrapped_name = getattr(property_.fget, '__name__', '') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1354 elif isinstance(property_, cached_property): # type: ignore 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

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

1356 

1357 return wrapped_name.startswith('_') and not wrapped_name.startswith('__') 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1358 

1359 

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

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

1362PropertyT = typing.TypeVar('PropertyT') 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1363 

1364 

1365@typing.overload 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1366def computed_field(func: PropertyT, /) -> PropertyT: ... 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1367 

1368 

1369@typing.overload 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1370def computed_field( 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1371 *, 

1372 alias: str | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1373 alias_priority: int | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1374 title: str | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1375 field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1376 description: str | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1377 deprecated: Deprecated | str | bool | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1378 examples: list[Any] | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1379 json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1380 repr: bool = True, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1381 return_type: Any = PydanticUndefined, 1rstuvwjkabcqlxyzABCmndefNOPKLMJDEFGHIopghi

1382) -> typing.Callable[[PropertyT], PropertyT]: ... 1jkabcqlmndefKLMJopghi

1383 

1384 

1385def computed_field( 1rstuvwjkabcxyzABCmndefNOPKLMJDEFGHIopghi

1386 func: PropertyT | None = None, 

1387 /, 

1388 *, 

1389 alias: str | None = None, 

1390 alias_priority: int | None = None, 

1391 title: str | None = None, 

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

1393 description: str | None = None, 

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

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

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

1397 repr: bool | None = None, 

1398 return_type: Any = PydanticUndefined, 

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

1400 """!!! abstract "Usage Documentation" 

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

1402 

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

1404 

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

1406 

1407 ```python 

1408 from pydantic import BaseModel, computed_field 

1409 

1410 class Rectangle(BaseModel): 

1411 width: int 

1412 length: int 

1413 

1414 @computed_field 

1415 @property 

1416 def area(self) -> int: 

1417 return self.width * self.length 

1418 

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

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

1421 ``` 

1422 

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

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

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

1426 

1427 !!! warning "Mypy Warning" 

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

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

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

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

1432 

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

1434 

1435 ```python 

1436 import random 

1437 

1438 from pydantic import BaseModel, computed_field 

1439 

1440 class Square(BaseModel): 

1441 width: float 

1442 

1443 @computed_field 

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

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

1446 

1447 @area.setter 

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

1449 self.width = new_area**0.5 

1450 

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

1452 def random_number(self) -> int: 

1453 return random.randint(0, 1_000) 

1454 

1455 square = Square(width=1.3) 

1456 

1457 # `random_number` does not appear in representation 

1458 print(repr(square)) 

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

1460 

1461 print(square.random_number) 

1462 #> 3 

1463 

1464 square.area = 4 

1465 

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

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

1468 ``` 

1469 

1470 !!! warning "Overriding with `computed_field`" 

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

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

1473 See the example below: 

1474 

1475 ```python 

1476 from pydantic import BaseModel, computed_field 

1477 

1478 class Parent(BaseModel): 

1479 a: str 

1480 

1481 try: 

1482 

1483 class Child(Parent): 

1484 @computed_field 

1485 @property 

1486 def a(self) -> str: 

1487 return 'new a' 

1488 

1489 except TypeError as e: 

1490 print(e) 

1491 ''' 

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

1493 ''' 

1494 ``` 

1495 

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

1497 

1498 ```python 

1499 from functools import cached_property 

1500 

1501 from pydantic import BaseModel, computed_field 

1502 

1503 class Model(BaseModel): 

1504 foo: int 

1505 

1506 @computed_field 

1507 @cached_property 

1508 def _private_cached_property(self) -> int: 

1509 return -self.foo 

1510 

1511 @computed_field 

1512 @property 

1513 def _private_property(self) -> int: 

1514 return -self.foo 

1515 

1516 m = Model(foo=1) 

1517 print(repr(m)) 

1518 #> Model(foo=1) 

1519 ``` 

1520 

1521 Args: 

1522 func: the function to wrap. 

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

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

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

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

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

1528 docstring 

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

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

1531 `deprecated` decorator. 

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

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

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

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

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

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

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

1539 objects. 

1540 

1541 Returns: 

1542 A proxy wrapper for the property. 

1543 """ 

1544 

1545 def dec(f: Any) -> Any: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1546 nonlocal description, deprecated, return_type, alias_priority 

1547 unwrapped = _decorators.unwrap_wrapped_function(f) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1548 

1549 if description is None and unwrapped.__doc__: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1550 description = inspect.cleandoc(unwrapped.__doc__) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1551 

1552 if deprecated is None and hasattr(unwrapped, '__deprecated__'): 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1553 deprecated = unwrapped.__deprecated__ 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1554 

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

1556 f = _decorators.ensure_property(f) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1557 alias_priority = (alias_priority or 2) if alias is not None else None 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1558 

1559 if repr is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1560 repr_: bool = not _wrapped_property_is_private(property_=f) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1561 else: 

1562 repr_ = repr 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1563 

1564 dec_info = ComputedFieldInfo( 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1565 f, 

1566 return_type, 

1567 alias, 

1568 alias_priority, 

1569 title, 

1570 field_title_generator, 

1571 description, 

1572 deprecated, 

1573 examples, 

1574 json_schema_extra, 

1575 repr_, 

1576 ) 

1577 return _decorators.PydanticDescriptorProxy(f, dec_info) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1578 

1579 if func is None: 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1580 return dec 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi

1581 else: 

1582 return dec(func) 1rstuvwjkabcqlxyzABCmndefDEFGHIopghi