Coverage for pydantic / main.py: 97.97%

483 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1"""Logic for creating models.""" 

2 

3from __future__ import annotations as _annotations 1pdaghiqebjklsrfcmno

4 

5import operator 1pdaghiqebjklsrfcmno

6import sys 1pdaghiqebjklsrfcmno

7import threading 1pdaghiqebjklsrfcmno

8import types 1pdaghiqebjklsrfcmno

9import warnings 1pdaghiqebjklsrfcmno

10from collections.abc import Callable, Generator, Mapping, MutableSet 1pdaghiqebjklsrfcmno

11from copy import copy, deepcopy 1pdaghiqebjklsrfcmno

12from functools import cached_property 1pdaghiqebjklsrfcmno

13from typing import ( 1pdaghiqebjklsrfcmno

14 TYPE_CHECKING, 

15 Any, 

16 ClassVar, 

17 Generic, 

18 Literal, 

19 Self, 

20 TypeAlias, 

21 TypeVar, 

22 Union, 

23 Unpack, 

24 cast, 

25 overload, 

26) 

27 

28from pydantic_core import PydanticUndefined, ValidationError 1pdaghiqebjklsrfcmno

29from typing_extensions import Sentinel, TypeForm 1pdaghiqebjklsrfcmno

30 

31from . import PydanticDeprecatedSince211 1pdaghiqebjklsrfcmno

32from ._internal import ( 1pdaghiqebjklsrfcmno

33 _config, 

34 _decorators, 

35 _fields, 

36 _forward_ref, 

37 _generics, 

38 _mock_val_ser, 

39 _model_construction, 

40 _namespace_utils, 

41 _repr, 

42 _typing_extra, 

43 _utils, 

44) 

45from .aliases import AliasChoices, AliasPath 1pdaghiqebjklsrfcmno

46from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler 1pdaghiqebjklsrfcmno

47from .config import ConfigDict, ExtraValues 1pdaghiqebjklsrfcmno

48from .errors import PydanticUndefinedAnnotation, PydanticUserError 1pdaghiqebjklsrfcmno

49from .json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema, JsonSchemaMode, JsonSchemaValue, model_json_schema 1pdaghiqebjklsrfcmno

50from .plugin._schema_validator import PluggableSchemaValidator 1pdaghiqebjklsrfcmno

51from .version import version_short 1pdaghiqebjklsrfcmno

52 

53if TYPE_CHECKING: 1pdaghiqebjklsrfcmno

54 from inspect import Signature 

55 

56 from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator 

57 

58 from ._internal._fields import PydanticExtraInfo 

59 from ._internal._namespace_utils import MappingNamespace 

60 from .fields import ComputedFieldInfo, FieldInfo, ModelPrivateAttr 

61 

62 

63__all__ = 'BaseModel', 'create_model' 1pdaghiqebjklsrfcmno

64 

65# Keep these type aliases available at runtime: 

66TupleGenerator: TypeAlias = Generator[tuple[str, Any], None, None] 1pdaghiqebjklsrfcmno

67# NOTE: In reality, `bool` should be replaced by `Literal[True]` but mypy fails to correctly apply bidirectional 

68# type inference (e.g. when using `{'a': {'b': True}}`): 

69# NOTE: Keep this type alias in sync with the stub definition in `pydantic-core`: 

70IncEx: TypeAlias = set[int] | set[str] | Mapping[int, Union['IncEx', bool]] | Mapping[str, Union['IncEx', bool]] 1pdaghiqebjklsrfcmno

71 

72_object_setattr = _model_construction.object_setattr 1pdaghiqebjklsrfcmno

73 

74_rebuild_lock = threading.RLock() 1pdaghiqebjklsrfcmno

75""" 1pdaghiqebjklsrfcmno

76A lock used to make model rebuilds thread-safe when first instantiating an incomplete model. 

77 

78Rebuilding a model isn't thread-safe (the class attributes are mutated during the rebuild, 

79while other threads may be reading them to perform validation/serialization), so `model_rebuild()` 

80calls are serialized using this lock. The lock is reentrant, as rebuilding a model can trigger the 

81rebuild of another one (e.g. when a generic origin is rebuilt during parametrization in 

82`__class_getitem__()`). For the same reason, the lock is global and not per-class: two threads 

83holding their own class's lock could otherwise request the other's and deadlock. 

84""" 

85 

86 

87def _check_frozen(model_cls: type[BaseModel], name: str, value: Any) -> None: 1pdaghiqebjklsrfcmno

88 if model_cls.model_config.get('frozen'): 1pdaghiqebjklsrfcmno

89 error_type = 'frozen_instance' 1pdaghiqebjklrfcmno

90 elif getattr(model_cls.__pydantic_fields__.get(name), 'frozen', False): 1pdaghiqebjklsrfcmno

91 error_type = 'frozen_field' 1pdaghiqebjklrfcmno

92 else: 

93 return 1pdaghiqebjklsrfcmno

94 

95 raise ValidationError.from_exception_data( 1pdaghiqebjklrfcmno

96 model_cls.__name__, [{'type': error_type, 'loc': (name,), 'input': value}] 

97 ) 

98 

99 

100def _model_field_setattr_handler(model: BaseModel, name: str, val: Any) -> None: 1pdaghiqebjklsrfcmno

101 model.__dict__[name] = val # pyright: ignore[reportIndexIssue] (https://github.com/microsoft/pyright/issues/11548) 1pdaghiqebjklsrfcmno

102 model.__pydantic_fields_set__.add(name) 1pdaghiqebjklsrfcmno

103 

104 

105def _private_setattr_handler(model: BaseModel, name: str, val: Any) -> None: 1pdaghiqebjklsrfcmno

106 if getattr(model, '__pydantic_private__', None) is None: 1pdaghiqebjklrfcmno

107 # While the attribute should be present at this point, this may not be the case if 

108 # users do unusual stuff with `model_post_init()` (which is where the `__pydantic_private__` 

109 # is initialized, by wrapping the user-defined `model_post_init()`), e.g. if they mock 

110 # the `model_post_init()` call. Ideally we should find a better way to init private attrs. 

111 object.__setattr__(model, '__pydantic_private__', {}) 1pdaghiqebjklrfcmno

112 model.__pydantic_private__[name] = val # pyright: ignore[reportOptionalSubscript] 1pdaghiqebjklrfcmno

113 

114 

115_ATTRIBUTE_MISSING = Sentinel('_ATTRIBUTE_MISSING') 1pdaghiqebjklsrfcmno

116 

117 

118_SIMPLE_SETATTR_HANDLERS: Mapping[str, Callable[[BaseModel, str, Any], None]] = { 1pdaghiqebjklsrfcmno

119 'model_field': _model_field_setattr_handler, 

120 'validate_assignment': lambda model, name, val: model.__pydantic_validator__.validate_assignment(model, name, val), # pyright: ignore[reportAssignmentType] 

121 'private': _private_setattr_handler, 

122 'cached_property': lambda model, name, val: model.__dict__.__setitem__(name, val), # pyright: ignore[reportAttributeAccessIssue] (https://github.com/microsoft/pyright/issues/11548) 

123 'extra_known': lambda model, name, val: _object_setattr(model, name, val), 

124} 

125 

126 

127class BaseModel(metaclass=_model_construction.ModelMetaclass): 1pdaghiqebjklsrfcmno

128 """!!! abstract "Usage Documentation" 

129 [Models](../concepts/models.md) 

130 

131 A base class for creating Pydantic models. 

132 

133 Attributes: 

134 __class_vars__: The names of the class variables defined on the model. 

135 __private_attributes__: Metadata about the private attributes of the model. 

136 __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model. 

137 

138 __pydantic_complete__: Whether model building is completed, or if there are still undefined fields. 

139 __pydantic_core_schema__: The core schema of the model. 

140 __pydantic_custom_init__: Whether the model has a custom `__init__` function. 

141 __pydantic_decorators__: Metadata containing the decorators defined on the model. 

142 __pydantic_generic_metadata__: A dictionary containing metadata about generic Pydantic models. 

143 The `origin` and `args` items map to the [`__origin__`][genericalias.__origin__] 

144 and [`__args__`][genericalias.__args__] attributes of [generic aliases][types-genericalias], 

145 and the `parameter` item maps to the `__parameter__` attribute of generic classes. 

146 __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models. 

147 __pydantic_post_init__: The name of the post-init method for the model, if defined. 

148 __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel]. 

149 __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model. 

150 __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model. 

151 

152 __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects. 

153 __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects. 

154 

155 __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] 

156 is set to `'allow'`. 

157 __pydantic_fields_set__: The names of fields explicitly set during instantiation. 

158 __pydantic_private__: Values of private attributes set on the model instance. 

159 """ 

160 

161 # Note: Many of the below class vars are defined in the metaclass, but we define them here for type checking purposes. 

162 

163 model_config: ClassVar[ConfigDict] = ConfigDict() 1pdaghiqebjklsrfcmno

164 """ 1pdaghiqebjklsrfcmno

165 Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict]. 

166 """ 

167 

168 __class_vars__: ClassVar[set[str]] 1pdaghiqebjklsrfcmno

169 """The names of the class variables defined on the model.""" 1pdaghiqebjklsrfcmno

170 

171 __private_attributes__: ClassVar[dict[str, ModelPrivateAttr]] 1pdaghiqebjklsrfcmno

172 """Metadata about the private attributes of the model.""" 1pdaghiqebjklsrfcmno

173 

174 __signature__: ClassVar[Signature] 1pdaghiqebjklsrfcmno

175 """The synthesized `__init__` [`Signature`][inspect.Signature] of the model.""" 1pdaghiqebjklsrfcmno

176 

177 __pydantic_complete__: ClassVar[bool] = False 1pdaghiqebjklsrfcmno

178 """Whether model building is completed, or if there are still undefined fields.""" 1pdaghiqebjklsrfcmno

179 

180 __pydantic_core_schema__: ClassVar[CoreSchema] 1pdaghiqebjklsrfcmno

181 """The core schema of the model.""" 1pdaghiqebjklsrfcmno

182 

183 __pydantic_custom_init__: ClassVar[bool] 1pdaghiqebjklsrfcmno

184 """Whether the model has a custom `__init__` method.""" 1pdaghiqebjklsrfcmno

185 

186 # Must be set for `GenerateSchema.model_schema` to work for a plain `BaseModel` annotation. 

187 __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos] = _decorators.DecoratorInfos() 1pdaghiqebjklsrfcmno

188 """Metadata containing the decorators defined on the model.""" 1pdaghiqebjklsrfcmno

189 

190 __pydantic_generic_metadata__: ClassVar[_generics.PydanticGenericMetadata] 1pdaghiqebjklsrfcmno

191 """A dictionary containing metadata about generic Pydantic models. 1pdaghiqebjklsrfcmno

192 

193 The `origin` and `args` items map to the [`__origin__`][genericalias.__origin__] 

194 and [`__args__`][genericalias.__args__] attributes of [generic aliases][types-genericalias], 

195 and the `parameter` item maps to the `__parameter__` attribute of generic classes. 

196 """ 

197 

198 __pydantic_parent_namespace__: ClassVar[dict[str, Any] | None] = None 1pdaghiqebjklsrfcmno

199 """Parent namespace of the model, used for automatic rebuilding of models.""" 1pdaghiqebjklsrfcmno

200 

201 __pydantic_post_init__: ClassVar[None | Literal['model_post_init']] 1pdaghiqebjklsrfcmno

202 """The name of the post-init method for the model, if defined.""" 1pdaghiqebjklsrfcmno

203 

204 __pydantic_root_model__: ClassVar[bool] = False 1pdaghiqebjklsrfcmno

205 """Whether the model is a [`RootModel`][pydantic.root_model.RootModel].""" 1pdaghiqebjklsrfcmno

206 

207 __pydantic_serializer__: ClassVar[SchemaSerializer] 1pdaghiqebjklsrfcmno

208 """The `pydantic-core` `SchemaSerializer` used to dump instances of the model.""" 1pdaghiqebjklsrfcmno

209 

210 __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator] 1pdaghiqebjklsrfcmno

211 """The `pydantic-core` `SchemaValidator` used to validate instances of the model.""" 1pdaghiqebjklsrfcmno

212 

213 __pydantic_fields__: ClassVar[dict[str, FieldInfo]] 1pdaghiqebjklsrfcmno

214 """A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.""" 1pdaghiqebjklsrfcmno

215 

216 __pydantic_setattr_handlers__: ClassVar[dict[str, Callable[[BaseModel, str, Any], None]]] 1pdaghiqebjklsrfcmno

217 """`__setattr__` handlers. Memoizing the handlers leads to a dramatic performance improvement in `__setattr__`""" 1pdaghiqebjklsrfcmno

218 

219 __pydantic_computed_fields__: ClassVar[dict[str, ComputedFieldInfo]] 1pdaghiqebjklsrfcmno

220 """A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.""" 1pdaghiqebjklsrfcmno

221 

222 __pydantic_extra_info__: ClassVar[PydanticExtraInfo | None] 1pdaghiqebjklsrfcmno

223 """A wrapper around the `__pydantic_extra__` annotation, if explicitly annotated on a model. 1pdaghiqebjklsrfcmno

224 

225 This is a private attribute, not meant to be used outside Pydantic. 

226 """ 

227 

228 __pydantic_extra__: dict[str, Any] | None = _model_construction.NoInitField(init=False) 1pdaghiqebjklsrfcmno

229 """A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] is set to `'allow'`.""" 1pdaghiqebjklsrfcmno

230 

231 __pydantic_fields_set__: MutableSet[str] = _model_construction.NoInitField(init=False) 1pdaghiqebjklsrfcmno

232 """The names of fields explicitly set during instantiation.""" 1pdaghiqebjklsrfcmno

233 

234 __pydantic_private__: dict[str, Any] | None = _model_construction.NoInitField(init=False) 1pdaghiqebjklsrfcmno

235 """Values of private attributes set on the model instance.""" 1pdaghiqebjklsrfcmno

236 

237 if not TYPE_CHECKING: 237 ↛ 255line 237 didn't jump to line 255 because the condition on line 237 was always true1pdaghiqebjklsrfcmno

238 # Prevent `BaseModel` from being instantiated directly 

239 # (defined in an `if not TYPE_CHECKING` block for clarity and to avoid type checking errors): 

240 __pydantic_core_schema__ = _mock_val_ser.MockCoreSchema( 1pdaghiqebjklsrfcmno

241 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly', 

242 code='base-model-instantiated', 

243 ) 

244 __pydantic_validator__ = _mock_val_ser.MockValSer( 1pdaghiqebjklsrfcmno

245 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly', 

246 val_or_ser='validator', 

247 code='base-model-instantiated', 

248 ) 

249 __pydantic_serializer__ = _mock_val_ser.MockValSer( 1pdaghiqebjklsrfcmno

250 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly', 

251 val_or_ser='serializer', 

252 code='base-model-instantiated', 

253 ) 

254 

255 __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__' 1pdaghiqebjklsrfcmno

256 

257 def __init__(self, /, **data: Any) -> None: 1pdaghiqebjklsrfcmno

258 """Create a new model by parsing and validating input data from keyword arguments. 

259 

260 Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be 

261 validated to form a valid model. 

262 

263 `self` is explicitly positional-only to allow `self` as a field name. 

264 """ 

265 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks 

266 __tracebackhide__ = True 1pdaghiqebjklsrfcmno

267 validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self) 1pdaghiqebjklsrfcmno

268 if self is not validated_self: 1pdaghiqebjklsrfcmno

269 warnings.warn( 1pdaghiqebjklrfcmno

270 'A custom validator is returning a value other than `self`.\n' 

271 "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n" 

272 f'See the `model_validator` docs (https://pydantic.dev/docs/validation/{version_short()}/concepts/validators/#model-validators) for more details.', 

273 stacklevel=2, 

274 ) 

275 

276 # The following line sets a flag that we use to determine when `__init__` gets overridden by the user 

277 __init__.__pydantic_base_init__ = True # pyright: ignore[reportFunctionMemberAccess] 1pdaghiqebjklsrfcmno

278 

279 @property 1pdaghiqebjklsrfcmno

280 def model_extra(self) -> dict[str, Any] | None: 1pdaghiqebjklsrfcmno

281 """Get extra fields set during validation. 

282 

283 Returns: 

284 A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`. 

285 """ 

286 return self.__pydantic_extra__ 1pdaghiqebjklrfcmno

287 

288 @property 1pdaghiqebjklsrfcmno

289 def model_fields_set(self) -> MutableSet[str]: 1pdaghiqebjklsrfcmno

290 """Returns the set of fields that have been explicitly set on this model instance. 

291 

292 Returns: 

293 A set of strings representing the fields that have been set, 

294 i.e. that were not filled from defaults. 

295 """ 

296 return self.__pydantic_fields_set__ 1pdaghiqebjklrfcmno

297 

298 @classmethod 1pdaghiqebjklsrfcmno

299 def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self: # noqa: C901 1pdaghiqebjklsrfcmno

300 """Creates a new instance of the `Model` class with validated data. 

301 

302 Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. 

303 Default values are respected, but no other validation is performed. 

304 

305 !!! note 

306 `model_construct()` generally respects the `model_config.extra` setting on the provided model. 

307 That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` 

308 and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. 

309 Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in 

310 an error if extra values are passed, but they will be ignored. 

311 

312 Args: 

313 _fields_set: A set of field names that were originally explicitly set during instantiation. If provided, 

314 this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute. 

315 Otherwise, the field names from the `values` argument will be used. 

316 values: Trusted or pre-validated data dictionary. 

317 

318 Returns: 

319 A new instance of the `Model` class with validated data. 

320 """ 

321 m = cls.__new__(cls) 1pdaghiqebjklrfcmno

322 fields_values: dict[str, Any] = {} 1pdaghiqebjklrfcmno

323 fields_set = set() 1pdaghiqebjklrfcmno

324 

325 for name, field in cls.__pydantic_fields__.items(): 1pdaghiqebjklrfcmno

326 if field.alias is not None and field.alias in values: 1pdaghiqebjklrfcmno

327 fields_values[name] = values.pop(field.alias) 1pdaghiqebjklrfcmno

328 fields_set.add(name) 1pdaghiqebjklrfcmno

329 

330 if (name not in fields_set) and (field.validation_alias is not None): 1pdaghiqebjklrfcmno

331 validation_aliases: list[str | AliasPath] = ( 1pdaghiqebjklrfcmno

332 field.validation_alias.choices 

333 if isinstance(field.validation_alias, AliasChoices) 

334 else [field.validation_alias] 

335 ) 

336 

337 for alias in validation_aliases: 1pdaghiqebjklrfcmno

338 if isinstance(alias, str) and alias in values: 1pdaghiqebjklrfcmno

339 fields_values[name] = values.pop(alias) 1pdaghiqebjklrfcmno

340 fields_set.add(name) 1pdaghiqebjklrfcmno

341 break 1pdaghiqebjklrfcmno

342 elif isinstance(alias, AliasPath): 1pdaghiqebjklrfcmno

343 value = alias.search_dict_for_path(values) 1pdaghiqebjklrfcmno

344 if value is not PydanticUndefined: 1pdaghiqebjklrfcmno

345 fields_values[name] = value 1pdaghiqebjklrfcmno

346 fields_set.add(name) 1pdaghiqebjklrfcmno

347 break 1pdaghiqebjklrfcmno

348 

349 if name not in fields_set: 1pdaghiqebjklrfcmno

350 if name in values: 1pdaghiqebjklrfcmno

351 fields_values[name] = values.pop(name) 1pdaghiqebjklrfcmno

352 fields_set.add(name) 1pdaghiqebjklrfcmno

353 elif not field.is_required(): 1pdaghiqebjklrfcmno

354 fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values) 1pdaghiqebjklrfcmno

355 if _fields_set is None: 1pdaghiqebjklrfcmno

356 _fields_set = fields_set 1pdaghiqebjklrfcmno

357 

358 _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None 1pdaghiqebjklrfcmno

359 _object_setattr(m, '__dict__', fields_values) 1pdaghiqebjklrfcmno

360 _object_setattr(m, '__pydantic_fields_set__', _fields_set) 1pdaghiqebjklrfcmno

361 if not cls.__pydantic_root_model__: 1pdaghiqebjklrfcmno

362 _object_setattr(m, '__pydantic_extra__', _extra) 1pdaghiqebjklrfcmno

363 _object_setattr(m, '__pydantic_private__', None) 1pdaghiqebjklrfcmno

364 

365 if cls.__pydantic_post_init__: 1pdaghiqebjklrfcmno

366 m.model_post_init(None) 1pdaghiqebjklrfcmno

367 # update private attributes with values set 

368 if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None: 1pdaghiqebjklrfcmno

369 for k, v in values.items(): 1pdaghiqebjklrfcmno

370 if k in m.__private_attributes__: 370 ↛ 369line 370 didn't jump to line 369 because the condition on line 370 was always true1pdaghiqebjklrfcmno

371 m.__pydantic_private__[k] = v 1pdaghiqebjklrfcmno

372 

373 return m 1pdaghiqebjklrfcmno

374 

375 def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self: 1pdaghiqebjklsrfcmno

376 """!!! abstract "Usage Documentation" 

377 [`model_copy`](../concepts/models.md#model-copy) 

378 

379 Returns a copy of the model. 

380 

381 !!! note 

382 The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This 

383 might have unexpected side effects if you store anything in it, on top of the model 

384 fields (e.g. the value of [cached properties][functools.cached_property]). 

385 

386 Args: 

387 update: A mapping of values to update the copied model. Updates are *not* 

388 applied recursively, and no validation is performed on updated values. 

389 Only the known fields are updated (if unknown keys are being passed and 

390 the model has [`extra`][pydantic.ConfigDict.extra] set to `'allow'`, they 

391 are added as extra data). 

392 deep: Whether a [deep copy][copy.deepcopy] of the model should be performed. 

393 

394 Returns: 

395 New model instance. 

396 """ 

397 if deep and update: 1pdaghiqebjklrfcmno

398 # Only deep copy the fields that won't be updated: 

399 copied = self.__copy__() 1pdaghiqebjklrfcmno

400 

401 # As we make separate `deepcopy()` calls, use a shared memo: 

402 memo: dict[int, Any] = {id(self): copied} 1pdaghiqebjklrfcmno

403 

404 # Selectively deepcopy fields that are not being updated: 

405 for k, v in copied.__dict__.items(): 1pdaghiqebjklrfcmno

406 if k not in update: 1pdaghiqebjklrfcmno

407 copied.__dict__[k] = deepcopy(v, memo) # pyright: ignore[reportIndexIssue] (https://github.com/microsoft/pyright/issues/11548) 1pdaghiqebjklrfcmno

408 if copied.__pydantic_extra__ is not None: 1pdaghiqebjklrfcmno

409 for k, v in copied.__pydantic_extra__.items(): 1pdaghiqebjklrfcmno

410 if k not in update: 1pdaghiqebjklrfcmno

411 copied.__pydantic_extra__[k] = deepcopy(v, memo) 1pdaghiqebjklrfcmno

412 if copied.__pydantic_private__ is not None: 1pdaghiqebjklrfcmno

413 # Same logic as `BaseModel.__deepcopy__()`: 

414 copied.__pydantic_private__ = deepcopy( 1pdaghiqebjklrfcmno

415 {k: v for k, v in copied.__pydantic_private__.items() if v is not PydanticUndefined}, 

416 memo, 

417 ) 

418 else: 

419 copied = self.__deepcopy__() if deep else self.__copy__() 1pdaghiqebjklrfcmno

420 

421 if update: 1pdaghiqebjklrfcmno

422 if self.model_config.get('extra') == 'allow': 1pdaghiqebjklrfcmno

423 for k, v in update.items(): 1pdaghiqebjklrfcmno

424 if k in self.__pydantic_fields__: 1pdaghiqebjklrfcmno

425 copied.__dict__[k] = v # pyright: ignore[reportIndexIssue] (https://github.com/microsoft/pyright/issues/11548) 1pdaghiqebjklrfcmno

426 else: 

427 if copied.__pydantic_extra__ is None: 1pdaghiqebjklrfcmno

428 copied.__pydantic_extra__ = {} 1pdaghiqebjklrfcmno

429 copied.__pydantic_extra__[k] = v 1pdaghiqebjklrfcmno

430 else: 

431 copied.__dict__.update(update) # pyright: ignore[reportAttributeAccessIssue] (https://github.com/microsoft/pyright/issues/11548) 1pdaghiqebjklrfcmno

432 

433 for name in update: 1pdaghiqebjklrfcmno

434 copied.__pydantic_fields_set__.add(name) 1pdaghiqebjklrfcmno

435 

436 return copied 1pdaghiqebjklrfcmno

437 

438 def model_dump( 1pdaghiqebjklsrfcmno

439 self, 

440 *, 

441 mode: Literal['json', 'python'] | str = 'python', 

442 include: IncEx | None = None, 

443 exclude: IncEx | None = None, 

444 context: Any | None = None, 

445 by_alias: bool | None = None, 

446 exclude_unset: bool = False, 

447 exclude_defaults: bool = False, 

448 exclude_none: bool = False, 

449 exclude_computed_fields: bool = False, 

450 round_trip: bool = False, 

451 warnings: bool | Literal['none', 'warn', 'error'] = True, 

452 fallback: Callable[[Any], Any] | None = None, 

453 serialize_as_any: bool = False, 

454 polymorphic_serialization: bool | None = None, 

455 ) -> dict[str, Any]: 

456 """!!! abstract "Usage Documentation" 

457 [`model_dump`](../concepts/serialization.md#python-mode) 

458 

459 Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. 

460 

461 Args: 

462 mode: The mode in which `to_python` should run. 

463 If mode is 'json', the output will only contain JSON serializable types. 

464 If mode is 'python', the output may contain non-JSON-serializable Python objects. 

465 include: A set of fields to include in the output. 

466 exclude: A set of fields to exclude from the output. 

467 context: Additional context to pass to the serializer. 

468 by_alias: Whether to use the field's alias in the dictionary key if defined. 

469 exclude_unset: Whether to exclude fields that have not been explicitly set. 

470 exclude_defaults: Whether to exclude fields that are set to their default value. 

471 exclude_none: Whether to exclude fields that have a value of `None`. 

472 exclude_computed_fields: Whether to exclude computed fields. 

473 While this can be useful for round-tripping, it is usually recommended to use the dedicated 

474 `round_trip` parameter instead. 

475 round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. 

476 warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, 

477 "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. 

478 fallback: A function to call when an unknown value is encountered. If not provided, 

479 a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. 

480 serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. 

481 polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call. 

482 

483 Returns: 

484 A dictionary representation of the model. 

485 """ 

486 return self.__pydantic_serializer__.to_python( 1pdaghiqebjklrfcmno

487 self, 

488 mode=mode, 

489 by_alias=by_alias, 

490 include=include, 

491 exclude=exclude, 

492 context=context, 

493 exclude_unset=exclude_unset, 

494 exclude_defaults=exclude_defaults, 

495 exclude_none=exclude_none, 

496 exclude_computed_fields=exclude_computed_fields, 

497 round_trip=round_trip, 

498 warnings=warnings, 

499 fallback=fallback, 

500 serialize_as_any=serialize_as_any, 

501 polymorphic_serialization=polymorphic_serialization, 

502 ) 

503 

504 def model_dump_json( 1pdaghiqebjklsrfcmno

505 self, 

506 *, 

507 indent: int | None = None, 

508 ensure_ascii: bool = False, 

509 include: IncEx | None = None, 

510 exclude: IncEx | None = None, 

511 context: Any | None = None, 

512 by_alias: bool | None = None, 

513 exclude_unset: bool = False, 

514 exclude_defaults: bool = False, 

515 exclude_none: bool = False, 

516 exclude_computed_fields: bool = False, 

517 round_trip: bool = False, 

518 warnings: bool | Literal['none', 'warn', 'error'] = True, 

519 fallback: Callable[[Any], Any] | None = None, 

520 serialize_as_any: bool = False, 

521 polymorphic_serialization: bool | None = None, 

522 ) -> str: 

523 """!!! abstract "Usage Documentation" 

524 [`model_dump_json`](../concepts/serialization.md#json-mode) 

525 

526 Generates a JSON representation of the model using Pydantic's `to_json` method. 

527 

528 Args: 

529 indent: Indentation to use in the JSON output. If None is passed, the output will be compact. 

530 ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped. 

531 If `False` (the default), these characters will be output as-is. 

532 include: Field(s) to include in the JSON output. 

533 exclude: Field(s) to exclude from the JSON output. 

534 context: Additional context to pass to the serializer. 

535 by_alias: Whether to serialize using field aliases. 

536 exclude_unset: Whether to exclude fields that have not been explicitly set. 

537 exclude_defaults: Whether to exclude fields that are set to their default value. 

538 exclude_none: Whether to exclude fields that have a value of `None`. 

539 exclude_computed_fields: Whether to exclude computed fields. 

540 While this can be useful for round-tripping, it is usually recommended to use the dedicated 

541 `round_trip` parameter instead. 

542 round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. 

543 warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, 

544 "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. 

545 fallback: A function to call when an unknown value is encountered. If not provided, 

546 a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. 

547 serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. 

548 polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call. 

549 

550 Returns: 

551 A JSON string representation of the model. 

552 """ 

553 return self.__pydantic_serializer__.to_json( 1pdaghiqebjklrfcmno

554 self, 

555 indent=indent, 

556 ensure_ascii=ensure_ascii, 

557 include=include, 

558 exclude=exclude, 

559 context=context, 

560 by_alias=by_alias, 

561 exclude_unset=exclude_unset, 

562 exclude_defaults=exclude_defaults, 

563 exclude_none=exclude_none, 

564 exclude_computed_fields=exclude_computed_fields, 

565 round_trip=round_trip, 

566 warnings=warnings, 

567 fallback=fallback, 

568 serialize_as_any=serialize_as_any, 

569 polymorphic_serialization=polymorphic_serialization, 

570 ).decode() 

571 

572 @classmethod 1pdaghiqebjklsrfcmno

573 def model_json_schema( 1pdaghiqebjklsrfcmno

574 cls, 

575 by_alias: bool | None = None, 

576 ref_template: str = DEFAULT_REF_TEMPLATE, 

577 schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, 

578 mode: JsonSchemaMode = 'validation', 

579 *, 

580 union_format: Literal['any_of', 'primitive_type_array'] = 'any_of', 

581 ) -> dict[str, Any]: 

582 """Generates a JSON schema for a model class. 

583 

584 Args: 

585 by_alias: Whether to use field aliases as keys in the generated JSON Schema. If `None` (the default), 

586 aliases are used unless disabled by the configuration (i.e. `validate_by_alias=False` for validation 

587 schemas). An explicit value takes precedence over the configuration. 

588 ref_template: The reference template. 

589 union_format: The format to use when combining schemas from unions together. Can be one of: 

590 

591 - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf) 

592 keyword to combine schemas (the default). 

593 - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type) 

594 keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive 

595 type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to 

596 `any_of`. 

597 schema_generator: To override the logic used to generate the JSON schema, as a subclass of 

598 `GenerateJsonSchema` with your desired modifications 

599 mode: The mode in which to generate the schema. 

600 

601 Returns: 

602 The JSON schema for the given model class. 

603 """ 

604 return model_json_schema( 1pdaghiqebjklrfcmno

605 cls, 

606 by_alias=by_alias, 

607 ref_template=ref_template, 

608 union_format=union_format, 

609 schema_generator=schema_generator, 

610 mode=mode, 

611 ) 

612 

613 @classmethod 1pdaghiqebjklsrfcmno

614 def model_parametrized_name(cls, params: tuple[TypeForm[Any], ...]) -> str: 1pdaghiqebjklsrfcmno

615 """Compute the class name for parametrizations of generic classes. 

616 

617 This method can be overridden to achieve a custom naming scheme for generic BaseModels. 

618 

619 Args: 

620 params: Tuple of types of the class. Given a generic class 

621 `Model` with 2 type variables and a concrete model `Model[str, int]`, 

622 the value `(str, int)` would be passed to `params`. 

623 

624 Returns: 

625 String representing the new class where `params` are passed to `cls` as type variables. 

626 

627 Raises: 

628 TypeError: Raised when trying to generate concrete names for non-generic models. 

629 """ 

630 if not issubclass(cls, Generic): 1pdaghiqebjklsrfcmno

631 raise TypeError('Concrete names should only be generated for generic models.') 1pdaghiqebjklrfcmno

632 

633 # Any strings received should represent forward references, so we handle them specially below. 

634 # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future, 

635 # we may be able to remove this special case. 

636 param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params] 1pdaghiqebjklsrfcmno

637 params_component = ', '.join(param_names) 1pdaghiqebjklsrfcmno

638 return f'{cls.__name__}[{params_component}]' 1pdaghiqebjklsrfcmno

639 

640 def model_post_init(self, context: Any, /) -> None: 1pdaghiqebjklsrfcmno

641 """Override this method to perform additional initialization after `__init__` and `model_construct`. 

642 This is useful if you want to do some validation that requires the entire model to be initialized. 

643 """ 

644 

645 @classmethod 1pdaghiqebjklsrfcmno

646 def model_rebuild( 1pdaghiqebjklsrfcmno

647 cls, 

648 *, 

649 force: bool = False, 

650 raise_errors: bool = True, 

651 _parent_namespace_depth: int = 2, 

652 _types_namespace: MappingNamespace | None = None, 

653 ) -> bool | None: 

654 """Try to rebuild the pydantic-core schema for the model. 

655 

656 This may be necessary when one of the annotations is a ForwardRef which could not be resolved during 

657 the initial attempt to build the schema, and automatic rebuilding fails. 

658 

659 Args: 

660 force: Whether to force the rebuilding of the model schema, defaults to `False`. 

661 raise_errors: Whether to raise errors, defaults to `True`. 

662 _parent_namespace_depth: The depth level of the parent namespace, defaults to 2. 

663 _types_namespace: The types namespace, defaults to `None`. 

664 

665 Returns: 

666 Returns `None` if the schema is already "complete" and rebuilding was not required. 

667 If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`. 

668 """ 

669 # As the rebuild lock is global (not per model class), avoid needlessly holding it if the model is 

670 # already complete: 

671 if cls.__pydantic_complete__ and not force: 1pdaghiqebjklsrfcmno

672 return None 1pdaghiqebjklsrfcmno

673 

674 with _rebuild_lock: 1pdaghiqebjklsrfcmno

675 # Re-check inside the lock, as another thread may have rebuilt the model while we were waiting: 

676 already_complete = cls.__pydantic_complete__ 1pdaghiqebjklsrfcmno

677 if already_complete and not force: 1pdaghiqebjklsrfcmno

678 return None 1pdaghiqebjklrfcmno

679 

680 cls.__pydantic_complete__ = False 1pdaghiqebjklsrfcmno

681 

682 if already_complete: 1pdaghiqebjklsrfcmno

683 # The existing validator/serializer must not be reused in pydantic-core, and the core schema 

684 # must not be reused in schema generation. If the model is already complete (i.e. `force=True`), 

685 # we set back mocks for the model (we could also delete the complete core schema/validator/serializer, 

686 # but this isn't thread-safe). 

687 _mock_val_ser.set_model_mocks(cls) 1pdaghiqebjklrfcmno

688 

689 if _types_namespace is not None: 1pdaghiqebjklsrfcmno

690 rebuild_ns = _types_namespace 1pdaghiqebjklrfcmno

691 elif _parent_namespace_depth > 0: 1pdaghiqebjklsrfcmno

692 rebuild_ns = ( 1pdaghiqebjklsrfcmno

693 _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {} 

694 ) 

695 else: 

696 rebuild_ns = {} 1pdaghiqebjklrfcmno

697 

698 parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {} 1pdaghiqebjklsrfcmno

699 

700 ns_resolver = _namespace_utils.NsResolver( 1pdaghiqebjklsrfcmno

701 parent_namespace={**rebuild_ns, **parent_ns}, 

702 ) 

703 

704 return _model_construction.complete_model_class( 1pdaghiqebjklsrfcmno

705 cls, 

706 _config.ConfigWrapper(cls.model_config, check=False), 

707 ns_resolver, 

708 raise_errors=raise_errors, 

709 # If the model was already complete, we don't need to call the hook again. 

710 call_on_complete_hook=not already_complete, 

711 is_force_rebuild=force, 

712 ) 

713 

714 @classmethod 1pdaghiqebjklsrfcmno

715 def model_validate( 1pdaghiqebjklsrfcmno

716 cls, 

717 obj: Any, 

718 *, 

719 strict: bool | None = None, 

720 extra: ExtraValues | None = None, 

721 from_attributes: bool | None = None, 

722 context: Any | None = None, 

723 by_alias: bool | None = None, 

724 by_name: bool | None = None, 

725 ) -> Self: 

726 """Validate a pydantic model instance. 

727 

728 If validation fails, the resulting [`ValidationError`][pydantic_core.ValidationError] reports the 

729 rejected locations and values. [Logfire](../integrations/logfire.md) can retain the complete validation 

730 input and surrounding trace context for production debugging (see 

731 [Troubleshooting validation errors](../errors/troubleshooting.md)). 

732 

733 Args: 

734 obj: The object to validate. 

735 strict: Whether to enforce types strictly. 

736 extra: Whether to ignore, allow, or forbid extra data during model validation. 

737 See the [`extra` configuration value][pydantic.ConfigDict.extra] for details. 

738 from_attributes: Whether to extract data from object attributes. 

739 context: Additional context to pass to the validator. 

740 by_alias: Whether to use the field's alias when validating against the provided input data. 

741 by_name: Whether to use the field's name when validating against the provided input data. 

742 

743 Raises: 

744 ValidationError: If the object could not be validated. 

745 

746 Returns: 

747 The validated model instance. 

748 """ 

749 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks 

750 __tracebackhide__ = True 1pdaghiqebjklsrfcmno

751 

752 if by_alias is False and by_name is not True: 1pdaghiqebjklsrfcmno

753 raise PydanticUserError( 1pdaghiqebjklrfcmno

754 'At least one of `by_alias` or `by_name` must be set to True.', 

755 code='validate-by-alias-and-name-false', 

756 ) 

757 

758 return cls.__pydantic_validator__.validate_python( 1pdaghiqebjklsrfcmno

759 obj, 

760 strict=strict, 

761 extra=extra, 

762 from_attributes=from_attributes, 

763 context=context, 

764 by_alias=by_alias, 

765 by_name=by_name, 

766 ) 

767 

768 @classmethod 1pdaghiqebjklsrfcmno

769 def model_validate_json( 1pdaghiqebjklsrfcmno

770 cls, 

771 json_data: str | bytes | bytearray, 

772 *, 

773 strict: bool | None = None, 

774 extra: ExtraValues | None = None, 

775 context: Any | None = None, 

776 by_alias: bool | None = None, 

777 by_name: bool | None = None, 

778 ) -> Self: 

779 """!!! abstract "Usage Documentation" 

780 [JSON Parsing](../concepts/json.md#json-parsing) 

781 

782 Validate the given JSON data against the Pydantic model. 

783 

784 A [`ValidationError`][pydantic_core.ValidationError] raised here reports the rejected locations and 

785 values, but may not retain the complete source document. Recording validations with 

786 [Logfire](../integrations/logfire.md) keeps the complete JSON input alongside the error — see 

787 [Troubleshooting validation errors](../errors/troubleshooting.md). 

788 

789 Args: 

790 json_data: The JSON data to validate. 

791 strict: Whether to enforce types strictly. 

792 extra: Whether to ignore, allow, or forbid extra data during model validation. 

793 See the [`extra` configuration value][pydantic.ConfigDict.extra] for details. 

794 context: Extra variables to pass to the validator. 

795 by_alias: Whether to use the field's alias when validating against the provided input data. 

796 by_name: Whether to use the field's name when validating against the provided input data. 

797 

798 Returns: 

799 The validated Pydantic model. 

800 

801 Raises: 

802 ValidationError: If `json_data` is not a JSON string or the object could not be validated. 

803 """ 

804 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks 

805 __tracebackhide__ = True 1pdaghiqebjklrfcmno

806 

807 if by_alias is False and by_name is not True: 1pdaghiqebjklrfcmno

808 raise PydanticUserError( 1pdaghiqebjklrfcmno

809 'At least one of `by_alias` or `by_name` must be set to True.', 

810 code='validate-by-alias-and-name-false', 

811 ) 

812 

813 return cls.__pydantic_validator__.validate_json( 1pdaghiqebjklrfcmno

814 json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name 

815 ) 

816 

817 @classmethod 1pdaghiqebjklsrfcmno

818 def model_validate_strings( 1pdaghiqebjklsrfcmno

819 cls, 

820 obj: Any, 

821 *, 

822 strict: bool | None = None, 

823 extra: ExtraValues | None = None, 

824 context: Any | None = None, 

825 by_alias: bool | None = None, 

826 by_name: bool | None = None, 

827 ) -> Self: 

828 """Validate the given object with string data against the Pydantic model. 

829 

830 Args: 

831 obj: The object containing string data to validate. 

832 strict: Whether to enforce types strictly. 

833 extra: Whether to ignore, allow, or forbid extra data during model validation. 

834 See the [`extra` configuration value][pydantic.ConfigDict.extra] for details. 

835 context: Extra variables to pass to the validator. 

836 by_alias: Whether to use the field's alias when validating against the provided input data. 

837 by_name: Whether to use the field's name when validating against the provided input data. 

838 

839 Returns: 

840 The validated Pydantic model. 

841 """ 

842 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks 

843 __tracebackhide__ = True 1pdaghiqebjklrfcmno

844 

845 if by_alias is False and by_name is not True: 1pdaghiqebjklrfcmno

846 raise PydanticUserError( 1pdaghiqebjklrfcmno

847 'At least one of `by_alias` or `by_name` must be set to True.', 

848 code='validate-by-alias-and-name-false', 

849 ) 

850 

851 return cls.__pydantic_validator__.validate_strings( 1pdaghiqebjklrfcmno

852 obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name 

853 ) 

854 

855 @classmethod 1pdaghiqebjklsrfcmno

856 def __get_pydantic_core_schema__(cls, source: type[BaseModel], handler: GetCoreSchemaHandler, /) -> CoreSchema: 1pdaghiqebjklsrfcmno

857 # This warning is only emitted when calling `super().__get_pydantic_core_schema__` from a model subclass. 

858 # In the generate schema logic, this method (`BaseModel.__get_pydantic_core_schema__`) is special cased to 

859 # *not* be called if not overridden. 

860 warnings.warn( 

861 'The `__get_pydantic_core_schema__` method of the `BaseModel` class is deprecated. If you are calling ' 

862 '`super().__get_pydantic_core_schema__` when overriding the method on a Pydantic model, consider using ' 

863 '`handler(source)` instead. However, note that overriding this method on models can lead to unexpected ' 

864 'side effects.', 

865 PydanticDeprecatedSince211, 

866 stacklevel=2, 

867 ) 

868 # Logic copied over from `GenerateSchema._model_schema`: 

869 schema = cls.__dict__.get('__pydantic_core_schema__') 

870 if schema is not None and not isinstance(schema, _mock_val_ser.MockCoreSchema): 

871 return cls.__pydantic_core_schema__ 

872 

873 return handler(source) 

874 

875 @classmethod 1pdaghiqebjklsrfcmno

876 def __get_pydantic_json_schema__( 1pdaghiqebjklsrfcmno

877 cls, 

878 core_schema: CoreSchema, 

879 handler: GetJsonSchemaHandler, 

880 /, 

881 ) -> JsonSchemaValue: 

882 """Hook into generating the model's JSON schema. 

883 

884 Args: 

885 core_schema: A `pydantic-core` CoreSchema. 

886 You can ignore this argument and call the handler with a new CoreSchema, 

887 wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`), 

888 or just call the handler with the original schema. 

889 handler: Call into Pydantic's internal JSON schema generation. 

890 This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema 

891 generation fails. 

892 Since this gets called by `BaseModel.model_json_schema` you can override the 

893 `schema_generator` argument to that function to change JSON schema generation globally 

894 for a type. 

895 

896 Returns: 

897 A JSON schema, as a Python object. 

898 """ 

899 return handler(core_schema) 1pdaghiqebjklrfcmno

900 

901 @classmethod 1pdaghiqebjklsrfcmno

902 def __pydantic_init_subclass__(cls, **kwargs: Any) -> None: 1pdaghiqebjklsrfcmno

903 """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass` 

904 only after basic class initialization is complete. In particular, attributes like `model_fields` will 

905 be present when this is called, but forward annotations are not guaranteed to be resolved yet, 

906 meaning that creating an instance of the class may fail. 

907 

908 This is necessary because `__init_subclass__` will always be called by `type.__new__`, 

909 and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that 

910 `type.__new__` was called in such a manner that the class would already be sufficiently initialized. 

911 

912 This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely, 

913 any kwargs passed to the class definition that aren't used internally by Pydantic. 

914 

915 Args: 

916 **kwargs: Any keyword arguments passed to the class definition that aren't used internally 

917 by Pydantic. 

918 

919 Note: 

920 You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__] 

921 instead, which is called once the class and its fields are fully initialized and ready for validation. 

922 """ 

923 

924 @classmethod 1pdaghiqebjklsrfcmno

925 def __pydantic_on_complete__(cls) -> None: 1pdaghiqebjklsrfcmno

926 """This is called once the class and its fields are fully initialized and ready to be used. 

927 

928 This typically happens when the class is created (just before 

929 [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass), 

930 except when forward annotations are used that could not immediately be resolved. 

931 In that case, it will be called later, when the model is rebuilt automatically or explicitly using 

932 [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild]. 

933 """ 

934 

935 def __class_getitem__( 1pdaghiqebjklsrfcmno

936 cls, typevar_values: TypeForm[Any] | tuple[TypeForm[Any], ...] 

937 ) -> type[BaseModel] | _forward_ref.PydanticRecursiveRef: 

938 cached = _generics.get_cached_generic_type_early(cls, typevar_values) 1pdaghiqebjklsrfcmno

939 if cached is not None: 1pdaghiqebjklsrfcmno

940 return cached 1pdaghiqebjklrfcmno

941 

942 if cls is BaseModel: 1pdaghiqebjklsrfcmno

943 raise TypeError('Type parameters should be placed on typing.Generic, not BaseModel') 1pdaghiqebjklrfcmno

944 if not hasattr(cls, '__parameters__'): 1pdaghiqebjklsrfcmno

945 raise TypeError(f'{cls} cannot be parametrized because it does not inherit from typing.Generic') 1pdaghiqebjklrfcmno

946 if not cls.__pydantic_generic_metadata__['parameters'] and Generic not in cls.__bases__: 1pdaghiqebjklsrfcmno

947 raise TypeError(f'{cls} is not a generic class') 1pdaghiqebjklrfcmno

948 

949 if not isinstance(typevar_values, tuple): 1pdaghiqebjklsrfcmno

950 typevar_values = (typevar_values,) 1pdaghiqebjklsrfcmno

951 

952 # For a model `class Model[T, U, V = int](BaseModel): ...` parametrized with `(str, bool)`, 

953 # this gives us `{T: str, U: bool, V: int}`: 

954 typevars_map = _generics.map_generic_model_arguments(cls, typevar_values) 1pdaghiqebjklsrfcmno

955 # We also update the provided args to use defaults values (`(str, bool)` becomes `(str, bool, int)`): 

956 typevar_values = tuple(v for v in typevars_map.values()) 1pdaghiqebjklsrfcmno

957 

958 if _utils.all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map: 1pdaghiqebjklsrfcmno

959 submodel = cls # if arguments are equal to parameters it's the same object 1pdaghiqebjklrfcmno

960 _generics.set_cached_generic_type(cls, typevar_values, submodel) 1pdaghiqebjklrfcmno

961 else: 

962 parent_args = cls.__pydantic_generic_metadata__['args'] 1pdaghiqebjklsrfcmno

963 if not parent_args: 1pdaghiqebjklsrfcmno

964 args = typevar_values 1pdaghiqebjklsrfcmno

965 else: 

966 args = tuple(_generics.replace_types(arg, typevars_map) for arg in parent_args) 1pdaghiqebjklrfcmno

967 

968 origin = cls.__pydantic_generic_metadata__['origin'] or cls 1pdaghiqebjklsrfcmno

969 model_name = origin.model_parametrized_name(args) 1pdaghiqebjklsrfcmno

970 params = tuple( 1pdaghiqebjklsrfcmno

971 dict.fromkeys(_generics.iter_contained_typevars(typevars_map.values())) 

972 ) # use dict as ordered set 

973 

974 with _generics.generic_recursion_self_type(origin, args) as maybe_self_type: 1pdaghiqebjklsrfcmno

975 cached = _generics.get_cached_generic_type_late(cls, typevar_values, origin, args) 1pdaghiqebjklsrfcmno

976 if cached is not None: 1pdaghiqebjklsrfcmno

977 return cached 1pdaghiqebjklrfcmno

978 

979 if maybe_self_type is not None: 1pdaghiqebjklsrfcmno

980 return maybe_self_type 1pdaghiqebjklrfcmno

981 

982 # Attempt to rebuild the origin in case new types have been defined 

983 try: 1pdaghiqebjklsrfcmno

984 # depth 2 gets you above this __class_getitem__ call. 

985 # Note that we explicitly provide the parent ns, otherwise 

986 # `model_rebuild` will use the parent ns no matter if it is the ns of a module. 

987 # We don't want this here, as this has unexpected effects when a model 

988 # is being parametrized during a forward annotation evaluation. 

989 parent_ns = _typing_extra.parent_frame_namespace(parent_depth=2) or {} 1pdaghiqebjklsrfcmno

990 origin.model_rebuild(_types_namespace=parent_ns) 1pdaghiqebjklsrfcmno

991 except PydanticUndefinedAnnotation: 1pdaghiqebjklrfcmno

992 # It's okay if it fails, it just means there are still undefined types 

993 # that could be evaluated later. 

994 pass 1pdaghiqebjklrfcmno

995 

996 submodel = _generics.create_generic_submodel(model_name, origin, args, params) 1pdaghiqebjklsrfcmno

997 

998 _generics.set_cached_generic_type(cls, typevar_values, submodel, origin, args) 1pdaghiqebjklsrfcmno

999 

1000 return submodel 1pdaghiqebjklsrfcmno

1001 

1002 def __copy__(self) -> Self: 1pdaghiqebjklsrfcmno

1003 """Returns a shallow copy of the model.""" 

1004 cls = type(self) 1pdaghiqebjklrfcmno

1005 m = cls.__new__(cls) 1pdaghiqebjklrfcmno

1006 _object_setattr(m, '__dict__', copy(self.__dict__)) 1pdaghiqebjklrfcmno

1007 _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__)) 1pdaghiqebjklrfcmno

1008 _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) 1pdaghiqebjklrfcmno

1009 

1010 if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: 1pdaghiqebjklrfcmno

1011 _object_setattr(m, '__pydantic_private__', None) 1pdaghiqebjklrfcmno

1012 else: 

1013 _object_setattr( 1pdaghiqebjklrfcmno

1014 m, 

1015 '__pydantic_private__', 

1016 {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, 

1017 ) 

1018 

1019 return m 1pdaghiqebjklrfcmno

1020 

1021 def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self: 1pdaghiqebjklsrfcmno

1022 """Returns a deep copy of the model.""" 

1023 if memo is None: 1pdaghiqebjklrfcmno

1024 memo = {} 1pdaghiqebjklrfcmno

1025 cls = type(self) 1pdaghiqebjklrfcmno

1026 m = cls.__new__(cls) 1pdaghiqebjklrfcmno

1027 memo[id(self)] = m 1pdaghiqebjklrfcmno

1028 _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo)) 1pdaghiqebjklrfcmno

1029 _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo)) 1pdaghiqebjklrfcmno

1030 # This next line doesn't need a deepcopy because __pydantic_fields_set__ only contains strings, 

1031 # and attempting a deepcopy would be marginally slower. 

1032 _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) 1pdaghiqebjklrfcmno

1033 

1034 if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: 1pdaghiqebjklrfcmno

1035 _object_setattr(m, '__pydantic_private__', None) 1pdaghiqebjklrfcmno

1036 else: 

1037 _object_setattr( 1pdaghiqebjklrfcmno

1038 m, 

1039 '__pydantic_private__', 

1040 deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo), 

1041 ) 

1042 

1043 return m 1pdaghiqebjklrfcmno

1044 

1045 if not TYPE_CHECKING: 1045 ↛ 1179line 1045 didn't jump to line 1179 because the condition on line 1045 was always true1pdaghiqebjklsrfcmno

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

1047 # The same goes for __setattr__ and __delattr__, see: https://github.com/pydantic/pydantic/issues/8643 

1048 

1049 def __getattr__(self, item: str) -> Any: 1pdaghiqebjklsrfcmno

1050 private_attributes = object.__getattribute__(self, '__private_attributes__') 1pdaghiqebjklrfcmno

1051 if item in private_attributes: 1pdaghiqebjklrfcmno

1052 attribute = private_attributes[item] 1pdaghiqebjklrfcmno

1053 if hasattr(attribute, '__get__'): 1pdaghiqebjklrfcmno

1054 return attribute.__get__(self, type(self)) # type: ignore 1pdaghiqebjklrfcmno

1055 

1056 try: 1pdaghiqebjklrfcmno

1057 # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items 

1058 return self.__pydantic_private__[item] # type: ignore 1pdaghiqebjklrfcmno

1059 except KeyError as exc: 1pdaghiqebjklrfcmno

1060 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc 1pdaghiqebjklrfcmno

1061 else: 

1062 # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized. 

1063 # See `BaseModel.__repr_args__` for more details 

1064 try: 1pdaghiqebjklrfcmno

1065 pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') 1pdaghiqebjklrfcmno

1066 except AttributeError: 1pdaghiqebjklrfcmno

1067 pydantic_extra = None 1pdaghiqebjklrfcmno

1068 

1069 if pydantic_extra and item in pydantic_extra: 1pdaghiqebjklrfcmno

1070 return pydantic_extra[item] 1pdaghiqebjklrfcmno

1071 else: 

1072 if hasattr(self.__class__, item): 1pdaghiqebjklrfcmno

1073 return super().__getattribute__(item) # Raises AttributeError if appropriate 1pdaghiqebjklrfcmno

1074 else: 

1075 # this is the current error 

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

1077 

1078 def __setattr__(self, name: str, value: Any) -> None: 1pdaghiqebjklsrfcmno

1079 if (setattr_handler := self.__pydantic_setattr_handlers__.get(name)) is not None: 1pdaghiqebjklsrfcmno

1080 setattr_handler(self, name, value) 1pdaghiqebjklrfcmno

1081 # if None is returned from _setattr_handler, the attribute was set directly 

1082 elif (setattr_handler := self._setattr_handler(name, value)) is not None: 1pdaghiqebjklsrfcmno

1083 setattr_handler(self, name, value) # call here to not memo on possibly unknown fields 1pdaghiqebjklsrfcmno

1084 self.__pydantic_setattr_handlers__[name] = setattr_handler # memoize the handler for faster access 1pdaghiqebjklsrfcmno

1085 

1086 def _setattr_handler(self, name: str, value: Any) -> Callable[[BaseModel, str, Any], None] | None: 1pdaghiqebjklsrfcmno

1087 """Get a handler for setting an attribute on the model instance. 

1088 

1089 Returns: 

1090 A handler for setting an attribute on the model instance. Used for memoization of the handler. 

1091 Memoizing the handlers leads to a dramatic performance improvement in `__setattr__` 

1092 Returns `None` when memoization is not safe, then the attribute is set directly. 

1093 """ 

1094 cls = self.__class__ 1pdaghiqebjklsrfcmno

1095 if name in cls.__class_vars__: 1pdaghiqebjklsrfcmno

1096 raise AttributeError( 1pdaghiqebjklrfcmno

1097 f'{name!r} is a ClassVar of `{cls.__name__}` and cannot be set on an instance. ' 

1098 f'If you want to set a value on the class, use `{cls.__name__}.{name} = value`.' 

1099 ) 

1100 elif not _fields.is_valid_field_name(name): 1pdaghiqebjklsrfcmno

1101 if (attribute := cls.__private_attributes__.get(name)) is not None: 1pdaghiqebjklrfcmno

1102 if hasattr(attribute, '__set__'): 1pdaghiqebjklrfcmno

1103 return lambda model, _name, val: attribute.__set__(model, val) 1pdaghiqebjklrfcmno

1104 else: 

1105 return _SIMPLE_SETATTR_HANDLERS['private'] 1pdaghiqebjklrfcmno

1106 else: 

1107 _object_setattr(self, name, value) 1pdaghiqebjklrfcmno

1108 return None # Can not return memoized handler with possibly freeform attr names 1pdaghiqebjklrfcmno

1109 

1110 attr = getattr(cls, name, _ATTRIBUTE_MISSING) 1pdaghiqebjklsrfcmno

1111 # NOTE: We currently special case properties and `cached_property`, but we might need 

1112 # to generalize this to all data/non-data descriptors at some point. For non-data descriptors 

1113 # (such as `cached_property`), it isn't obvious though. `cached_property` caches the value 

1114 # to the instance's `__dict__`, but other non-data descriptors might do things differently. 

1115 if isinstance(attr, cached_property): 1pdaghiqebjklsrfcmno

1116 return _SIMPLE_SETATTR_HANDLERS['cached_property'] 1pdaghiqebjklrfcmno

1117 

1118 _check_frozen(cls, name, value) 1pdaghiqebjklsrfcmno

1119 

1120 # We allow properties to be set only on non frozen models for now (to match dataclasses). 

1121 # This can be changed if it ever gets requested. 

1122 if isinstance(attr, property): 1pdaghiqebjklsrfcmno

1123 return lambda model, _name, val: attr.__set__(model, val) 1pdaghiqebjklrfcmno

1124 elif cls.model_config.get('validate_assignment'): 1pdaghiqebjklsrfcmno

1125 return _SIMPLE_SETATTR_HANDLERS['validate_assignment'] 1pdaghiqebjklrfcmno

1126 elif name not in cls.__pydantic_fields__: 1pdaghiqebjklsrfcmno

1127 if cls.model_config.get('extra') != 'allow': 1pdaghiqebjklrfcmno

1128 # TODO - matching error 

1129 raise ValueError(f'"{cls.__name__}" object has no field "{name}"') 1pdaghiqebjklrfcmno

1130 elif attr is _ATTRIBUTE_MISSING: 1pdaghiqebjklrfcmno

1131 # attribute does not exist, so put it in extra 

1132 self.__pydantic_extra__[name] = value 1pdaghiqebjklrfcmno

1133 self.__pydantic_fields_set__.add(name) 1pdaghiqebjklrfcmno

1134 return None # Can not return memoized handler with possibly freeform attr names 1pdaghiqebjklrfcmno

1135 else: 

1136 # attribute _does_ exist, and was not in extra, so update it 

1137 return _SIMPLE_SETATTR_HANDLERS['extra_known'] 1pdaghiqebjklrfcmno

1138 else: 

1139 return _SIMPLE_SETATTR_HANDLERS['model_field'] 1pdaghiqebjklsrfcmno

1140 

1141 def __delattr__(self, item: str) -> Any: 1pdaghiqebjklsrfcmno

1142 cls = self.__class__ 1pdaghiqebjklrfcmno

1143 

1144 if item in self.__private_attributes__: 1pdaghiqebjklrfcmno

1145 attribute = self.__private_attributes__[item] 1pdaghiqebjklrfcmno

1146 if hasattr(attribute, '__delete__'): 1pdaghiqebjklrfcmno

1147 attribute.__delete__(self) # type: ignore 1pdaghiqebjklrfcmno

1148 return 1pdaghiqebjklrfcmno

1149 

1150 try: 1pdaghiqebjklrfcmno

1151 # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items 

1152 del self.__pydantic_private__[item] # type: ignore 1pdaghiqebjklrfcmno

1153 return 1pdaghiqebjklrfcmno

1154 except KeyError as exc: 1pdaghiqebjklrfcmno

1155 raise AttributeError(f'{cls.__name__!r} object has no attribute {item!r}') from exc 1pdaghiqebjklrfcmno

1156 

1157 # Allow cached properties to be deleted (even if the class is frozen): 

1158 attr = getattr(cls, item, None) 1pdaghiqebjklrfcmno

1159 if isinstance(attr, cached_property): 1pdaghiqebjklrfcmno

1160 return object.__delattr__(self, item) 1pdaghiqebjklrfcmno

1161 

1162 _check_frozen(cls, name=item, value=None) 1pdaghiqebjklrfcmno

1163 

1164 if item in self.__pydantic_fields__: 1pdaghiqebjklrfcmno

1165 object.__delattr__(self, item) 1pdaghiqebjklrfcmno

1166 elif self.__pydantic_extra__ is not None and item in self.__pydantic_extra__: 1pdaghiqebjklrfcmno

1167 del self.__pydantic_extra__[item] 1pdaghiqebjklrfcmno

1168 else: 

1169 try: 1pdaghiqebjklrfcmno

1170 object.__delattr__(self, item) 1pdaghiqebjklrfcmno

1171 except AttributeError: 1pdaghiqebjklrfcmno

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

1173 

1174 # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by 

1175 # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block: 

1176 def __replace__(self, **changes: Any) -> Self: 1pdaghiqebjklsrfcmno

1177 return self.model_copy(update=changes) 1aghibjklcmno

1178 

1179 def __getstate__(self) -> dict[Any, Any]: 1pdaghiqebjklsrfcmno

1180 private = self.__pydantic_private__ 1pdaghiqebjklrfcmno

1181 if private: 1pdaghiqebjklrfcmno

1182 private = {k: v for k, v in private.items() if v is not PydanticUndefined} 1pdaghiqebjklrfcmno

1183 return { 1pdaghiqebjklrfcmno

1184 '__dict__': self.__dict__, 

1185 '__pydantic_extra__': self.__pydantic_extra__, 

1186 '__pydantic_fields_set__': self.__pydantic_fields_set__, 

1187 '__pydantic_private__': private, 

1188 } 

1189 

1190 def __setstate__(self, state: dict[Any, Any]) -> None: 1pdaghiqebjklsrfcmno

1191 _object_setattr(self, '__pydantic_fields_set__', state.get('__pydantic_fields_set__', {})) 1pdaghiqebjklrfcmno

1192 _object_setattr(self, '__pydantic_extra__', state.get('__pydantic_extra__', {})) 1pdaghiqebjklrfcmno

1193 _object_setattr(self, '__pydantic_private__', state.get('__pydantic_private__', {})) 1pdaghiqebjklrfcmno

1194 _object_setattr(self, '__dict__', state.get('__dict__', {})) 1pdaghiqebjklrfcmno

1195 

1196 if not TYPE_CHECKING: 1pdaghiqebjklsrfcmno

1197 

1198 def __eq__(self, other: Any) -> bool: 1pdaghiqebjklsrfcmno

1199 if isinstance(other, BaseModel): 1pdaghiqebjklrfcmno

1200 # When comparing instances of generic types for equality, as long as all field values are equal, 

1201 # only require their generic origin types to be equal, rather than exact type equality. 

1202 # This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1). 

1203 self_type = self.__pydantic_generic_metadata__['origin'] or self.__class__ 1pdaghiqebjklrfcmno

1204 other_type = other.__pydantic_generic_metadata__['origin'] or other.__class__ 1pdaghiqebjklrfcmno

1205 

1206 # Perform common checks first 

1207 if not ( 1ghijklmno

1208 self_type is other_type 

1209 and getattr(self, '__pydantic_private__', None) == getattr(other, '__pydantic_private__', None) 

1210 # We need to assume `None` and `{}` are equivalent, because extra behavior 

1211 # can be controlled at validation time: 

1212 and (self.__pydantic_extra__ or {}) == (other.__pydantic_extra__ or {}) 

1213 ): 

1214 return False 1pdaghiqebjklrfcmno

1215 

1216 # We only want to compare pydantic fields but ignoring fields is costly. 

1217 # We'll perform a fast check first, and fallback only when needed 

1218 # See GH-7444 and GH-7825 for rationale and a performance benchmark 

1219 

1220 # First, do the fast (and sometimes faulty) __dict__ comparison 

1221 if self.__dict__ == other.__dict__: 1pdaghiqebjklrfcmno

1222 # If the check above passes, then pydantic fields are equal, we can return early 

1223 return True 1pdaghiqebjklrfcmno

1224 

1225 # We don't want to trigger unnecessary costly filtering of __dict__ on all unequal objects, so we return 

1226 # early if there are no keys to ignore (we would just return False later on anyway) 

1227 model_fields = type(self).__pydantic_fields__.keys() 1pdaghiqebjklrfcmno

1228 if self.__dict__.keys() <= model_fields and other.__dict__.keys() <= model_fields: 1pdaghiqebjklrfcmno

1229 return False 1pdaghiqebjklrfcmno

1230 

1231 # If we reach here, there are non-pydantic-fields keys, mapped to unequal values, that we need to ignore 

1232 # Resort to costly filtering of the __dict__ objects 

1233 # We use operator.itemgetter because it is much faster than dict comprehensions 

1234 # NOTE: Contrary to standard python class and instances, when the Model class has a default value for an 

1235 # attribute and the model instance doesn't have a corresponding attribute, accessing the missing attribute 

1236 # raises an error in BaseModel.__getattr__ instead of returning the class attribute 

1237 # So we can use operator.itemgetter() instead of operator.attrgetter() 

1238 getter = operator.itemgetter(*model_fields) if model_fields else lambda _: _utils._SENTINEL 1pdaghiqebjklrfcmno

1239 try: 1pdaghiqebjklrfcmno

1240 return getter(self.__dict__) == getter(other.__dict__) 1pdaghiqebjklrfcmno

1241 except KeyError: 

1242 # In rare cases (such as when using the deprecated BaseModel.copy() method), 

1243 # the __dict__ may not contain all model fields, which is how we can get here. 

1244 # getter(self.__dict__) is much faster than any 'safe' method that accounts 

1245 # for missing keys, and wrapping it in a `try` doesn't slow things down much 

1246 # in the common case. 

1247 self_fields_proxy = _utils.SafeGetItemProxy(self.__dict__) 

1248 other_fields_proxy = _utils.SafeGetItemProxy(other.__dict__) 

1249 return getter(self_fields_proxy) == getter(other_fields_proxy) 

1250 

1251 # other instance is not a BaseModel 

1252 else: 

1253 return NotImplemented # delegate to the other item in the comparison 1pdaghiqebjklrfcmno

1254 

1255 if TYPE_CHECKING: 1pdaghiqebjklsrfcmno

1256 # We put `__init_subclass__` in a TYPE_CHECKING block because, even though we want the type-checking benefits 

1257 # described in the signature of `__init_subclass__` below, we don't want to modify the default behavior of 

1258 # subclass initialization. 

1259 

1260 def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]): 

1261 """This signature is included purely to help type-checkers check arguments to class declaration, which 

1262 provides a way to conveniently set model_config key/value pairs. 

1263 

1264 ```python 

1265 from pydantic import BaseModel 

1266 

1267 class MyModel(BaseModel, extra='allow'): ... 

1268 ``` 

1269 

1270 However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any 

1271 of the config arguments, and will only receive any keyword arguments passed during class initialization 

1272 that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.) 

1273 

1274 Args: 

1275 **kwargs: Keyword arguments passed to the class definition, which set model_config 

1276 

1277 Note: 

1278 You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called 

1279 *after* the class is fully initialized. 

1280 """ 

1281 

1282 def __iter__(self) -> TupleGenerator: 1pdaghiqebjklsrfcmno

1283 """So `dict(model)` works.""" 

1284 yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')] 1pdaghiqebjklrfcmno

1285 extra = self.__pydantic_extra__ 1pdaghiqebjklrfcmno

1286 if extra: 1pdaghiqebjklrfcmno

1287 yield from extra.items() 1pdaghiqebjklrfcmno

1288 

1289 def __repr__(self) -> str: 1pdaghiqebjklsrfcmno

1290 return f'{self.__repr_name__()}({self.__repr_str__(", ")})' 1pdaghiqebjklrfcmno

1291 

1292 def __repr_args__(self) -> _repr.ReprArgs: 1pdaghiqebjklsrfcmno

1293 # Eagerly create the repr of computed fields, as this may trigger access of cached properties and as such 

1294 # modify the instance's `__dict__`. If we don't do it now, it could happen when iterating over the `__dict__` 

1295 # below if the instance happens to be referenced in a field, and would modify the `__dict__` size *during* iteration. 

1296 computed_fields_repr_args = [ 1pdaghiqebjklrfcmno

1297 (k, getattr(self, k)) for k, v in self.__pydantic_computed_fields__.items() if v.repr 

1298 ] 

1299 

1300 for k, v in self.__dict__.items(): 1pdaghiqebjklrfcmno

1301 field = self.__pydantic_fields__.get(k) 1pdaghiqebjklrfcmno

1302 if field and field.repr: 1pdaghiqebjklrfcmno

1303 if v is not self: 1pdaghiqebjklrfcmno

1304 yield k, v 1pdaghiqebjklrfcmno

1305 else: 

1306 yield k, self.__repr_recursion__(v) 1pdaghiqebjklrfcmno

1307 # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized. 

1308 # This can happen if a `ValidationError` is raised during initialization and the instance's 

1309 # repr is generated as part of the exception handling. Therefore, we use `getattr` here 

1310 # with a fallback, even though the type hints indicate the attribute will always be present. 

1311 try: 1pdaghiqebjklrfcmno

1312 pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') 1pdaghiqebjklrfcmno

1313 except AttributeError: 1pdaghiqebjklrfcmno

1314 pydantic_extra = None 1pdaghiqebjklrfcmno

1315 

1316 if pydantic_extra is not None: 1pdaghiqebjklrfcmno

1317 yield from ((k, v) for k, v in pydantic_extra.items()) 1pdaghiqebjklrfcmno

1318 yield from computed_fields_repr_args 1pdaghiqebjklrfcmno

1319 

1320 # take logic from `_repr.Representation` without the side effects of inheritance, see #5740 

1321 __repr_name__ = _repr.Representation.__repr_name__ 1pdaghiqebjklsrfcmno

1322 __repr_recursion__ = _repr.Representation.__repr_recursion__ 1pdaghiqebjklsrfcmno

1323 __repr_str__ = _repr.Representation.__repr_str__ 1pdaghiqebjklsrfcmno

1324 __pretty__ = _repr.Representation.__pretty__ 1pdaghiqebjklsrfcmno

1325 __rich_repr__ = _repr.Representation.__rich_repr__ 1pdaghiqebjklsrfcmno

1326 

1327 def __str__(self) -> str: 1pdaghiqebjklsrfcmno

1328 return self.__repr_str__(' ') 1pdaghiqebjklrfcmno

1329 

1330 

1331ModelT = TypeVar('ModelT', bound=BaseModel) 1pdaghiqebjklsrfcmno

1332 

1333_CREATE_MODEL_RESERVED_NAMESPACE_KEYS: dict[str, str] = { 1pdaghiqebjklsrfcmno

1334 '__annotations__': 'field definitions', 

1335 '__module__': 'the `__module__` argument', 

1336 '__qualname__': 'the `__qualname__` argument', 

1337 '__doc__': 'the `__doc__` argument', 

1338 'model_config': 'the `__config__` argument', 

1339} 

1340"""Keys that can't be provided in the `__namespace__` argument of `create_model()`, mapped to the argument to use instead.""" 1pdaghiqebjklsrfcmno

1341 

1342 

1343@overload 1pdaghiqebjklsrfcmno

1344def create_model( 1pdaghiqebjklsrfcmno

1345 model_name: str, 1daebsfc

1346 /, 

1347 *, 

1348 __config__: ConfigDict | None = None, 1pdaghiqebjklsrfcmno

1349 __doc__: str | None = None, 1pdaghiqebjklsrfcmno

1350 __base__: None = None, 1pdaghiqebjklsrfcmno

1351 __module__: str = __name__, 1pdaghiqebjklsrfcmno

1352 __namespace__: dict[str, Any] | None = None, 1pdaghiqebjklsrfcmno

1353 __cls_kwargs__: dict[str, Any] | None = None, 1pdaghiqebjklsrfcmno

1354 __qualname__: str | None = None, 1pdaghiqebjklsrfcmno

1355 **field_definitions: TypeForm[Any] | tuple[TypeForm[Any], Any], 1daebsfc

1356) -> type[BaseModel]: ... 1daebsfc

1357 

1358 

1359@overload 1pdaghiqebjklsrfcmno

1360def create_model( 1pdaghiqebjklsrfcmno

1361 model_name: str, 1daebsfc

1362 /, 

1363 *, 

1364 __config__: ConfigDict | None = None, 1pdaghiqebjklsrfcmno

1365 __doc__: str | None = None, 1pdaghiqebjklsrfcmno

1366 __base__: type[ModelT] | tuple[type[ModelT], ...], 1daebsfc

1367 __module__: str = __name__, 1pdaghiqebjklsrfcmno

1368 __namespace__: dict[str, Any] | None = None, 1pdaghiqebjklsrfcmno

1369 __cls_kwargs__: dict[str, Any] | None = None, 1pdaghiqebjklsrfcmno

1370 __qualname__: str | None = None, 1pdaghiqebjklsrfcmno

1371 **field_definitions: TypeForm[Any] | tuple[TypeForm[Any], Any], 1daebsfc

1372) -> type[ModelT]: ... 1daebsfc

1373 

1374 

1375def create_model( # noqa: C901 1pdaghiqebjklsrfcmno

1376 model_name: str, 

1377 /, 

1378 *, 

1379 __config__: ConfigDict | None = None, 

1380 __doc__: str | None = None, 

1381 __base__: type[ModelT] | tuple[type[ModelT], ...] | None = None, 

1382 __module__: str | None = None, 

1383 __namespace__: dict[str, Any] | None = None, 

1384 __cls_kwargs__: dict[str, Any] | None = None, 

1385 __qualname__: str | None = None, 

1386 **field_definitions: TypeForm[Any] | tuple[TypeForm[Any], Any], 

1387) -> type[ModelT]: 

1388 """!!! abstract "Usage Documentation" 

1389 [Dynamic Model Creation](../concepts/models.md#dynamic-model-creation) 

1390 

1391 Dynamically creates and returns a new Pydantic model. In other words, `create_model()` dynamically creates a 

1392 subclass of [`BaseModel`][pydantic.BaseModel]. 

1393 

1394 !!! warning 

1395 This function may execute arbitrary code contained in field annotations, if string references need to be evaluated. 

1396 

1397 See [Security implications of introspecting annotations](https://docs.python.org/3/library/annotationlib.html#annotationlib-security) for more information. 

1398 

1399 Args: 

1400 model_name: The name of the newly created model. 

1401 __config__: The configuration of the new model. 

1402 __doc__: The docstring of the new model. 

1403 __base__: The base class or classes for the new model. 

1404 __module__: The name of the module that the model belongs to; 

1405 if `None`, the value is taken from `sys._getframe(1)` 

1406 __namespace__: A dictionary of attributes to add to the class namespace of the new model, such as 

1407 [validators](../concepts/validators.md), methods or [computed fields][pydantic.computed_field]. 

1408 Keys must not clash with any of the field names or with the attributes that have a dedicated argument 

1409 (`__annotations__`, `__module__`, `__qualname__`, `__doc__` and `model_config`). 

1410 

1411 /// version-added | v2.14 

1412 /// 

1413 

1414 /// version-removed | v3 

1415 The `__validators__` argument was removed, use `__namespace__` instead. 

1416 /// 

1417 __cls_kwargs__: A dictionary of keyword arguments for class creation, such as `metaclass`. 

1418 __qualname__: The qualified name of the newly created model. 

1419 **field_definitions: Field definitions of the new model. Either: 

1420 

1421 - a single element, representing the type annotation of the field. 

1422 - a two-tuple, the first element being the type and the second element the assigned value 

1423 (either a default or the [`Field()`][pydantic.Field] function). 

1424 

1425 Returns: 

1426 The new [model][pydantic.BaseModel]. 

1427 

1428 Raises: 

1429 PydanticUserError: If `__base__` and `__config__` are both passed, 

1430 or if a key of `__namespace__` clashes with a field name or with an attribute that has a dedicated argument. 

1431 """ 

1432 if __base__ is None: 1pdaghiqebjklsrfcmno

1433 __base__ = (cast('type[ModelT]', BaseModel),) 1pdaghiqebjklrfcmno

1434 elif not isinstance(__base__, tuple): 1pdaghiqebjklsrfcmno

1435 __base__ = (__base__,) 1pdaghiqebjklsrfcmno

1436 

1437 if '__validators__' in field_definitions: 1pdaghiqebjklsrfcmno

1438 # Would otherwise be silently ignored, as a dunder field definition. 

1439 # TODO: remove this check in the next major version: 

1440 raise TypeError( 1pdaghiqebjklrfcmno

1441 "create_model() got an unexpected keyword argument '__validators__', use '__namespace__' instead" 

1442 ) 

1443 

1444 __cls_kwargs__ = __cls_kwargs__ or {} 1pdaghiqebjklsrfcmno

1445 

1446 fields: dict[str, Any] = {} 1pdaghiqebjklsrfcmno

1447 annotations: dict[str, Any] = {} 1pdaghiqebjklsrfcmno

1448 

1449 for f_name, f_def in field_definitions.items(): 1pdaghiqebjklsrfcmno

1450 if isinstance(f_def, tuple): 1pdaghiqebjklrfcmno

1451 if len(f_def) != 2: 1pdaghiqebjklrfcmno

1452 raise PydanticUserError( 1pdaghiqebjklrfcmno

1453 f'Field definition for {f_name!r} should a single element representing the type or a two-tuple, the first element ' 

1454 'being the type and the second element the assigned value (either a default or the `Field()` function).', 

1455 code='create-model-field-definitions', 

1456 ) 

1457 

1458 annotations[f_name] = f_def[0] 1pdaghiqebjklrfcmno

1459 fields[f_name] = f_def[1] 1pdaghiqebjklrfcmno

1460 else: 

1461 annotations[f_name] = f_def 1pdaghiqebjklrfcmno

1462 

1463 if __namespace__: 1pdaghiqebjklsrfcmno

1464 if clashing_names := field_definitions.keys() & __namespace__.keys(): 1pdaghiqebjklrfcmno

1465 raise PydanticUserError( 1pdaghiqebjklrfcmno

1466 f'Field name(s) {", ".join(map(repr, sorted(clashing_names)))} clash with keys of the `__namespace__` argument.', 

1467 code='create-model-namespace', 

1468 ) 

1469 for key, argument in _CREATE_MODEL_RESERVED_NAMESPACE_KEYS.items(): 1pdaghiqebjklrfcmno

1470 if key in __namespace__: 1pdaghiqebjklrfcmno

1471 raise PydanticUserError( 1pdaghiqebjklrfcmno

1472 f'{key!r} is not allowed as a key of the `__namespace__` argument, use {argument} instead.', 

1473 code='create-model-namespace', 

1474 ) 

1475 

1476 if __module__ is None: 1pdaghiqebjklsrfcmno

1477 f = sys._getframe(1) 1pdaghiqebjklsrfcmno

1478 __module__ = f.f_globals['__name__'] 1pdaghiqebjklsrfcmno

1479 

1480 namespace: dict[str, Any] = {'__annotations__': annotations, '__module__': __module__} 1pdaghiqebjklsrfcmno

1481 if __doc__: 1pdaghiqebjklsrfcmno

1482 namespace['__doc__'] = __doc__ 1pdaghiqebjklrfcmno

1483 if __qualname__ is not None: 1pdaghiqebjklsrfcmno

1484 namespace['__qualname__'] = __qualname__ 1pdaghiqebjklrfcmno

1485 if __namespace__: 1pdaghiqebjklsrfcmno

1486 namespace.update(__namespace__) 1pdaghiqebjklrfcmno

1487 namespace.update(fields) 1pdaghiqebjklsrfcmno

1488 if __config__: 1pdaghiqebjklsrfcmno

1489 namespace['model_config'] = __config__ 1pdaghiqebjklrfcmno

1490 resolved_bases = types.resolve_bases(__base__) 1pdaghiqebjklsrfcmno

1491 meta, ns, kwds = types.prepare_class(model_name, resolved_bases, kwds=__cls_kwargs__) 1pdaghiqebjklsrfcmno

1492 if resolved_bases is not __base__: 1pdaghiqebjklsrfcmno

1493 ns['__orig_bases__'] = __base__ 1pdaghiqebjklrfcmno

1494 namespace.update(ns) 1pdaghiqebjklsrfcmno

1495 

1496 return meta( 1pdaghiqebjklsrfcmno

1497 model_name, 

1498 resolved_bases, 

1499 namespace, 

1500 __pydantic_reset_parent_namespace__=False, 

1501 _create_model_module=__module__, 

1502 **kwds, 

1503 )