Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pydantic/main.py: 42%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

599 statements  

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

2 

3# Because `dict` is in the local namespace of the `BaseModel` class, we use `Dict` for annotations. 

4# TODO v3 fallback to `dict` when the deprecated `dict` method gets removed. 

5# ruff: noqa: UP035 

6 

7from __future__ import annotations as _annotations 

8 

9import operator 

10import sys 

11import threading 

12import types 

13import warnings 

14from collections.abc import Generator, Mapping 

15from copy import copy, deepcopy 

16from functools import cached_property 

17from typing import ( 

18 TYPE_CHECKING, 

19 Any, 

20 Callable, 

21 ClassVar, 

22 Dict, 

23 Generic, 

24 Literal, 

25 TypeVar, 

26 Union, 

27 cast, 

28 overload, 

29) 

30 

31import pydantic_core 

32import typing_extensions 

33from pydantic_core import PydanticUndefined, ValidationError 

34from typing_extensions import Self, Sentinel, TypeAlias, TypeForm, Unpack 

35 

36from . import PydanticDeprecatedSince20, PydanticDeprecatedSince211 

37from ._internal import ( 

38 _config, 

39 _decorators, 

40 _fields, 

41 _forward_ref, 

42 _generics, 

43 _mock_val_ser, 

44 _model_construction, 

45 _namespace_utils, 

46 _repr, 

47 _typing_extra, 

48 _utils, 

49) 

50from ._migration import getattr_migration 

51from .aliases import AliasChoices, AliasPath 

52from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler 

53from .config import ConfigDict, ExtraValues 

54from .errors import PydanticUndefinedAnnotation, PydanticUserError 

55from .json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema, JsonSchemaMode, JsonSchemaValue, model_json_schema 

56from .plugin._schema_validator import PluggableSchemaValidator 

57from .version import version_short 

58 

59if TYPE_CHECKING: 

60 from inspect import Signature 

61 from pathlib import Path 

62 

63 from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator 

64 

65 from ._internal._fields import PydanticExtraInfo 

66 from ._internal._namespace_utils import MappingNamespace 

67 from ._internal._utils import AbstractSetIntStr, MappingIntStrAny 

68 from .deprecated.parse import Protocol as DeprecatedParseProtocol 

69 from .fields import ComputedFieldInfo, FieldInfo, ModelPrivateAttr 

70 

71 

72__all__ = 'BaseModel', 'create_model' 

73 

74# Keep these type aliases available at runtime: 

75TupleGenerator: TypeAlias = Generator[tuple[str, Any], None, None] 

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

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

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

79IncEx: TypeAlias = set[int] | set[str] | Mapping[int, Union['IncEx', bool]] | Mapping[str, Union['IncEx', bool]] 

80 

81_object_setattr = _model_construction.object_setattr 

82 

83_rebuild_lock = threading.RLock() 

84""" 

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

86 

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

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

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

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

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

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

93""" 

94 

95 

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

97 if model_cls.model_config.get('frozen'): 

98 error_type = 'frozen_instance' 

99 elif getattr(model_cls.__pydantic_fields__.get(name), 'frozen', False): 

100 error_type = 'frozen_field' 

101 else: 

102 return 

103 

104 raise ValidationError.from_exception_data( 

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

106 ) 

107 

108 

109def _model_field_setattr_handler(model: BaseModel, name: str, val: Any) -> None: 

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

111 model.__pydantic_fields_set__.add(name) 

112 

113 

114def _private_setattr_handler(model: BaseModel, name: str, val: Any) -> None: 

115 if getattr(model, '__pydantic_private__', None) is None: 

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

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

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

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

120 object.__setattr__(model, '__pydantic_private__', {}) 

121 model.__pydantic_private__[name] = val # pyright: ignore[reportOptionalSubscript] 

122 

123 

124_ATTRIBUTE_MISSING = Sentinel('_ATTRIBUTE_MISSING') 

125 

126 

127_SIMPLE_SETATTR_HANDLERS: Mapping[str, Callable[[BaseModel, str, Any], None]] = { 

128 'model_field': _model_field_setattr_handler, 

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

130 'private': _private_setattr_handler, 

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

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

133} 

134 

135 

136class BaseModel(metaclass=_model_construction.ModelMetaclass): 

137 """!!! abstract "Usage Documentation" 

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

139 

140 A base class for creating Pydantic models. 

141 

142 Attributes: 

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

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

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

146 

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

148 __pydantic_core_schema__: The core schema of the model. 

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

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

151 This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1. 

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

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

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

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

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

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

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

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

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

161 

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

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

164 

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

166 is set to `'allow'`. 

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

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

169 """ 

170 

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

172 

173 model_config: ClassVar[ConfigDict] = ConfigDict() 

174 """ 

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

176 """ 

177 

178 __class_vars__: ClassVar[set[str]] 

179 """The names of the class variables defined on the model.""" 

180 

181 __private_attributes__: ClassVar[Dict[str, ModelPrivateAttr]] # noqa: UP006 

182 """Metadata about the private attributes of the model.""" 

183 

184 __signature__: ClassVar[Signature] 

185 """The synthesized `__init__` [`Signature`][inspect.Signature] of the model.""" 

186 

187 __pydantic_complete__: ClassVar[bool] = False 

188 """Whether model building is completed, or if there are still undefined fields.""" 

189 

190 __pydantic_core_schema__: ClassVar[CoreSchema] 

191 """The core schema of the model.""" 

192 

193 __pydantic_custom_init__: ClassVar[bool] 

194 """Whether the model has a custom `__init__` method.""" 

195 

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

197 __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos] = _decorators.DecoratorInfos() 

198 """Metadata containing the decorators defined on the model. 

199 This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.""" 

200 

201 __pydantic_generic_metadata__: ClassVar[_generics.PydanticGenericMetadata] 

202 """A dictionary containing metadata about generic Pydantic models. 

203 

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

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

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

207 """ 

208 

209 __pydantic_parent_namespace__: ClassVar[Dict[str, Any] | None] = None # noqa: UP006 

210 """Parent namespace of the model, used for automatic rebuilding of models.""" 

211 

212 __pydantic_post_init__: ClassVar[None | Literal['model_post_init']] 

213 """The name of the post-init method for the model, if defined.""" 

214 

215 __pydantic_root_model__: ClassVar[bool] = False 

216 """Whether the model is a [`RootModel`][pydantic.root_model.RootModel].""" 

217 

218 __pydantic_serializer__: ClassVar[SchemaSerializer] 

219 """The `pydantic-core` `SchemaSerializer` used to dump instances of the model.""" 

220 

221 __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator] 

222 """The `pydantic-core` `SchemaValidator` used to validate instances of the model.""" 

223 

224 __pydantic_fields__: ClassVar[Dict[str, FieldInfo]] # noqa: UP006 

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

226 This replaces `Model.__fields__` from Pydantic V1. 

227 """ 

228 

229 __pydantic_setattr_handlers__: ClassVar[Dict[str, Callable[[BaseModel, str, Any], None]]] # noqa: UP006 

230 """`__setattr__` handlers. Memoizing the handlers leads to a dramatic performance improvement in `__setattr__`""" 

231 

232 __pydantic_computed_fields__: ClassVar[Dict[str, ComputedFieldInfo]] # noqa: UP006 

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

234 

235 __pydantic_extra_info__: ClassVar[PydanticExtraInfo | None] 

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

237 

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

239 """ 

240 

241 __pydantic_extra__: Dict[str, Any] | None = _model_construction.NoInitField(init=False) # noqa: UP006 

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

243 

244 __pydantic_fields_set__: set[str] = _model_construction.NoInitField(init=False) 

245 """The names of fields explicitly set during instantiation.""" 

246 

247 __pydantic_private__: Dict[str, Any] | None = _model_construction.NoInitField(init=False) # noqa: UP006 

248 """Values of private attributes set on the model instance.""" 

249 

250 if not TYPE_CHECKING: 

251 # Prevent `BaseModel` from being instantiated directly 

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

253 __pydantic_core_schema__ = _mock_val_ser.MockCoreSchema( 

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

255 code='base-model-instantiated', 

256 ) 

257 __pydantic_validator__ = _mock_val_ser.MockValSer( 

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

259 val_or_ser='validator', 

260 code='base-model-instantiated', 

261 ) 

262 __pydantic_serializer__ = _mock_val_ser.MockValSer( 

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

264 val_or_ser='serializer', 

265 code='base-model-instantiated', 

266 ) 

267 

268 __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__' 

269 

270 def __init__(self, /, **data: Any) -> None: 

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

272 

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

274 validated to form a valid model. 

275 

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

277 """ 

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

279 __tracebackhide__ = True 

280 validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self) 

281 if self is not validated_self: 

282 warnings.warn( 

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

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

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

286 stacklevel=2, 

287 ) 

288 

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

290 __init__.__pydantic_base_init__ = True # pyright: ignore[reportFunctionMemberAccess] 

291 

292 @_utils.deprecated_instance_property 

293 @classmethod 

294 def model_fields(cls) -> Dict[str, FieldInfo]: # noqa: UP006 

295 """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances. 

296 

297 !!! warning 

298 Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. 

299 Instead, you should access this attribute from the model class. 

300 """ 

301 return getattr(cls, '__pydantic_fields__', {}) 

302 

303 @_utils.deprecated_instance_property 

304 @classmethod 

305 def model_computed_fields(cls) -> Dict[str, ComputedFieldInfo]: # noqa: UP006 

306 """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances. 

307 

308 !!! warning 

309 Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. 

310 Instead, you should access this attribute from the model class. 

311 """ 

312 return getattr(cls, '__pydantic_computed_fields__', {}) 

313 

314 @property 

315 def model_extra(self) -> Dict[str, Any] | None: # noqa: UP006 

316 """Get extra fields set during validation. 

317 

318 Returns: 

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

320 """ 

321 return self.__pydantic_extra__ 

322 

323 @property 

324 def model_fields_set(self) -> set[str]: 

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

326 

327 Returns: 

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

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

330 """ 

331 return self.__pydantic_fields_set__ 

332 

333 @classmethod 

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

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

336 

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

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

339 

340 !!! note 

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

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

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

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

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

346 

347 Args: 

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

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

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

351 values: Trusted or pre-validated data dictionary. 

352 

353 Returns: 

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

355 """ 

356 m = cls.__new__(cls) 

357 fields_values: dict[str, Any] = {} 

358 fields_set = set() 

359 

360 for name, field in cls.__pydantic_fields__.items(): 

361 if field.alias is not None and field.alias in values: 

362 fields_values[name] = values.pop(field.alias) 

363 fields_set.add(name) 

364 

365 if (name not in fields_set) and (field.validation_alias is not None): 

366 validation_aliases: list[str | AliasPath] = ( 

367 field.validation_alias.choices 

368 if isinstance(field.validation_alias, AliasChoices) 

369 else [field.validation_alias] 

370 ) 

371 

372 for alias in validation_aliases: 

373 if isinstance(alias, str) and alias in values: 

374 fields_values[name] = values.pop(alias) 

375 fields_set.add(name) 

376 break 

377 elif isinstance(alias, AliasPath): 

378 value = alias.search_dict_for_path(values) 

379 if value is not PydanticUndefined: 

380 fields_values[name] = value 

381 fields_set.add(name) 

382 break 

383 

384 if name not in fields_set: 

385 if name in values: 

386 fields_values[name] = values.pop(name) 

387 fields_set.add(name) 

388 elif not field.is_required(): 

389 fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values) 

390 if _fields_set is None: 

391 _fields_set = fields_set 

392 

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

394 _object_setattr(m, '__dict__', fields_values) 

395 _object_setattr(m, '__pydantic_fields_set__', _fields_set) 

396 if not cls.__pydantic_root_model__: 

397 _object_setattr(m, '__pydantic_extra__', _extra) 

398 _object_setattr(m, '__pydantic_private__', None) 

399 

400 if cls.__pydantic_post_init__: 

401 m.model_post_init(None) 

402 # update private attributes with values set 

403 if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None: 

404 for k, v in values.items(): 

405 if k in m.__private_attributes__: 

406 m.__pydantic_private__[k] = v 

407 

408 return m 

409 

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

411 """!!! abstract "Usage Documentation" 

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

413 

414 Returns a copy of the model. 

415 

416 !!! note 

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

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

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

420 

421 Args: 

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

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

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

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

426 are added as extra data). 

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

428 

429 Returns: 

430 New model instance. 

431 """ 

432 if deep and update: 

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

434 copied = self.__copy__() 

435 

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

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

438 

439 # Selectively deepcopy fields that are not being updated: 

440 for k, v in copied.__dict__.items(): 

441 if k not in update: 

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

443 if copied.__pydantic_extra__ is not None: 

444 for k, v in copied.__pydantic_extra__.items(): 

445 if k not in update: 

446 copied.__pydantic_extra__[k] = deepcopy(v, memo) 

447 if copied.__pydantic_private__ is not None: 

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

449 copied.__pydantic_private__ = deepcopy( 

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

451 memo, 

452 ) 

453 else: 

454 copied = self.__deepcopy__() if deep else self.__copy__() 

455 

456 if update: 

457 if self.model_config.get('extra') == 'allow': 

458 for k, v in update.items(): 

459 if k in self.__pydantic_fields__: 

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

461 else: 

462 if copied.__pydantic_extra__ is None: 

463 copied.__pydantic_extra__ = {} 

464 copied.__pydantic_extra__[k] = v 

465 else: 

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

467 

468 copied.__pydantic_fields_set__.update(update.keys()) 

469 

470 return copied 

471 

472 def model_dump( 

473 self, 

474 *, 

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

476 include: IncEx | None = None, 

477 exclude: IncEx | None = None, 

478 context: Any | None = None, 

479 by_alias: bool | None = None, 

480 exclude_unset: bool = False, 

481 exclude_defaults: bool = False, 

482 exclude_none: bool = False, 

483 exclude_computed_fields: bool = False, 

484 round_trip: bool = False, 

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

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

487 serialize_as_any: bool = False, 

488 polymorphic_serialization: bool | None = None, 

489 ) -> Dict[str, Any]: # noqa: UP006 

490 """!!! abstract "Usage Documentation" 

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

492 

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

494 

495 Args: 

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

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

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

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

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

501 context: Additional context to pass to the serializer. 

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

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

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

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

506 exclude_computed_fields: Whether to exclude computed fields. 

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

508 `round_trip` parameter instead. 

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

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

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

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

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

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

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

516 

517 Returns: 

518 A dictionary representation of the model. 

519 """ 

520 return self.__pydantic_serializer__.to_python( 

521 self, 

522 mode=mode, 

523 by_alias=by_alias, 

524 include=include, 

525 exclude=exclude, 

526 context=context, 

527 exclude_unset=exclude_unset, 

528 exclude_defaults=exclude_defaults, 

529 exclude_none=exclude_none, 

530 exclude_computed_fields=exclude_computed_fields, 

531 round_trip=round_trip, 

532 warnings=warnings, 

533 fallback=fallback, 

534 serialize_as_any=serialize_as_any, 

535 polymorphic_serialization=polymorphic_serialization, 

536 ) 

537 

538 def model_dump_json( 

539 self, 

540 *, 

541 indent: int | None = None, 

542 ensure_ascii: bool = False, 

543 include: IncEx | None = None, 

544 exclude: IncEx | None = None, 

545 context: Any | None = None, 

546 by_alias: bool | None = None, 

547 exclude_unset: bool = False, 

548 exclude_defaults: bool = False, 

549 exclude_none: bool = False, 

550 exclude_computed_fields: bool = False, 

551 round_trip: bool = False, 

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

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

554 serialize_as_any: bool = False, 

555 polymorphic_serialization: bool | None = None, 

556 ) -> str: 

557 """!!! abstract "Usage Documentation" 

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

559 

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

561 

562 Args: 

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

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

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

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

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

568 context: Additional context to pass to the serializer. 

569 by_alias: Whether to serialize using field aliases. 

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

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

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

573 exclude_computed_fields: Whether to exclude computed fields. 

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

575 `round_trip` parameter instead. 

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

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

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

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

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

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

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

583 

584 Returns: 

585 A JSON string representation of the model. 

586 """ 

587 return self.__pydantic_serializer__.to_json( 

588 self, 

589 indent=indent, 

590 ensure_ascii=ensure_ascii, 

591 include=include, 

592 exclude=exclude, 

593 context=context, 

594 by_alias=by_alias, 

595 exclude_unset=exclude_unset, 

596 exclude_defaults=exclude_defaults, 

597 exclude_none=exclude_none, 

598 exclude_computed_fields=exclude_computed_fields, 

599 round_trip=round_trip, 

600 warnings=warnings, 

601 fallback=fallback, 

602 serialize_as_any=serialize_as_any, 

603 polymorphic_serialization=polymorphic_serialization, 

604 ).decode() 

605 

606 @classmethod 

607 def model_json_schema( 

608 cls, 

609 by_alias: bool | None = None, 

610 ref_template: str = DEFAULT_REF_TEMPLATE, 

611 schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, 

612 mode: JsonSchemaMode = 'validation', 

613 *, 

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

615 ) -> Dict[str, Any]: # noqa: UP006 

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

617 

618 Args: 

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

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

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

622 ref_template: The reference template. 

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

624 

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

626 keyword to combine schemas (the default). 

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

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

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

630 `any_of`. 

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

632 `GenerateJsonSchema` with your desired modifications 

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

634 

635 Returns: 

636 The JSON schema for the given model class. 

637 """ 

638 return model_json_schema( 

639 cls, 

640 by_alias=by_alias, 

641 ref_template=ref_template, 

642 union_format=union_format, 

643 schema_generator=schema_generator, 

644 mode=mode, 

645 ) 

646 

647 @classmethod 

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

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

650 

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

652 

653 Args: 

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

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

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

657 

658 Returns: 

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

660 

661 Raises: 

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

663 """ 

664 if not issubclass(cls, Generic): 

665 raise TypeError('Concrete names should only be generated for generic models.') 

666 

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

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

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

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

671 params_component = ', '.join(param_names) 

672 return f'{cls.__name__}[{params_component}]' 

673 

674 def model_post_init(self, context: Any, /) -> None: 

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

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

677 """ 

678 

679 @classmethod 

680 def model_rebuild( 

681 cls, 

682 *, 

683 force: bool = False, 

684 raise_errors: bool = True, 

685 _parent_namespace_depth: int = 2, 

686 _types_namespace: MappingNamespace | None = None, 

687 ) -> bool | None: 

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

689 

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

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

692 

693 Args: 

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

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

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

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

698 

699 Returns: 

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

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

702 """ 

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

704 # already complete: 

705 if cls.__pydantic_complete__ and not force: 

706 return None 

707 

708 with _rebuild_lock: 

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

710 already_complete = cls.__pydantic_complete__ 

711 if already_complete and not force: 

712 return None 

713 

714 cls.__pydantic_complete__ = False 

715 

716 if already_complete: 

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

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

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

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

721 _mock_val_ser.set_model_mocks(cls) 

722 

723 if _types_namespace is not None: 

724 rebuild_ns = _types_namespace 

725 elif _parent_namespace_depth > 0: 

726 rebuild_ns = ( 

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

728 ) 

729 else: 

730 rebuild_ns = {} 

731 

732 parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {} 

733 

734 ns_resolver = _namespace_utils.NsResolver( 

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

736 ) 

737 

738 return _model_construction.complete_model_class( 

739 cls, 

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

741 ns_resolver, 

742 raise_errors=raise_errors, 

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

744 call_on_complete_hook=not already_complete, 

745 is_force_rebuild=force, 

746 ) 

747 

748 @classmethod 

749 def model_validate( 

750 cls, 

751 obj: Any, 

752 *, 

753 strict: bool | None = None, 

754 extra: ExtraValues | None = None, 

755 from_attributes: bool | None = None, 

756 context: Any | None = None, 

757 by_alias: bool | None = None, 

758 by_name: bool | None = None, 

759 ) -> Self: 

760 """Validate a pydantic model instance. 

761 

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

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

764 input and surrounding trace context for production debugging (see 

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

766 

767 Args: 

768 obj: The object to validate. 

769 strict: Whether to enforce types strictly. 

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

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

772 from_attributes: Whether to extract data from object attributes. 

773 context: Additional context to pass to the validator. 

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

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

776 

777 Raises: 

778 ValidationError: If the object could not be validated. 

779 

780 Returns: 

781 The validated model instance. 

782 """ 

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

784 __tracebackhide__ = True 

785 

786 if by_alias is False and by_name is not True: 

787 raise PydanticUserError( 

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

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

790 ) 

791 

792 return cls.__pydantic_validator__.validate_python( 

793 obj, 

794 strict=strict, 

795 extra=extra, 

796 from_attributes=from_attributes, 

797 context=context, 

798 by_alias=by_alias, 

799 by_name=by_name, 

800 ) 

801 

802 @classmethod 

803 def model_validate_json( 

804 cls, 

805 json_data: str | bytes | bytearray, 

806 *, 

807 strict: bool | None = None, 

808 extra: ExtraValues | None = None, 

809 context: Any | None = None, 

810 by_alias: bool | None = None, 

811 by_name: bool | None = None, 

812 ) -> Self: 

813 """!!! abstract "Usage Documentation" 

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

815 

816 Validate the given JSON data against the Pydantic model. 

817 

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

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

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

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

822 

823 Args: 

824 json_data: The JSON data to validate. 

825 strict: Whether to enforce types strictly. 

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

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

828 context: Extra variables to pass to the validator. 

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

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

831 

832 Returns: 

833 The validated Pydantic model. 

834 

835 Raises: 

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

837 """ 

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

839 __tracebackhide__ = True 

840 

841 if by_alias is False and by_name is not True: 

842 raise PydanticUserError( 

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

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

845 ) 

846 

847 return cls.__pydantic_validator__.validate_json( 

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

849 ) 

850 

851 @classmethod 

852 def model_validate_strings( 

853 cls, 

854 obj: Any, 

855 *, 

856 strict: bool | None = None, 

857 extra: ExtraValues | None = None, 

858 context: Any | None = None, 

859 by_alias: bool | None = None, 

860 by_name: bool | None = None, 

861 ) -> Self: 

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

863 

864 Args: 

865 obj: The object containing string data to validate. 

866 strict: Whether to enforce types strictly. 

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

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

869 context: Extra variables to pass to the validator. 

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

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

872 

873 Returns: 

874 The validated Pydantic model. 

875 """ 

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

877 __tracebackhide__ = True 

878 

879 if by_alias is False and by_name is not True: 

880 raise PydanticUserError( 

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

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

883 ) 

884 

885 return cls.__pydantic_validator__.validate_strings( 

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

887 ) 

888 

889 @classmethod 

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

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

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

893 # *not* be called if not overridden. 

894 warnings.warn( 

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

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

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

898 'side effects.', 

899 PydanticDeprecatedSince211, 

900 stacklevel=2, 

901 ) 

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

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

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

905 return cls.__pydantic_core_schema__ 

906 

907 return handler(source) 

908 

909 @classmethod 

910 def __get_pydantic_json_schema__( 

911 cls, 

912 core_schema: CoreSchema, 

913 handler: GetJsonSchemaHandler, 

914 /, 

915 ) -> JsonSchemaValue: 

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

917 

918 Args: 

919 core_schema: A `pydantic-core` CoreSchema. 

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

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

922 or just call the handler with the original schema. 

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

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

925 generation fails. 

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

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

928 for a type. 

929 

930 Returns: 

931 A JSON schema, as a Python object. 

932 """ 

933 return handler(core_schema) 

934 

935 @classmethod 

936 def __pydantic_init_subclass__(cls, **kwargs: Any) -> None: 

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

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

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

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

941 

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

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

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

945 

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

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

948 

949 Args: 

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

951 by Pydantic. 

952 

953 Note: 

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

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

956 """ 

957 

958 @classmethod 

959 def __pydantic_on_complete__(cls) -> None: 

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

961 

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

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

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

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

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

967 """ 

968 

969 def __class_getitem__( 

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

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

972 cached = _generics.get_cached_generic_type_early(cls, typevar_values) 

973 if cached is not None: 

974 return cached 

975 

976 if cls is BaseModel: 

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

978 if not hasattr(cls, '__parameters__'): 

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

980 if not cls.__pydantic_generic_metadata__['parameters'] and Generic not in cls.__bases__: 

981 raise TypeError(f'{cls} is not a generic class') 

982 

983 if not isinstance(typevar_values, tuple): 

984 typevar_values = (typevar_values,) 

985 

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

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

988 typevars_map = _generics.map_generic_model_arguments(cls, typevar_values) 

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

990 typevar_values = tuple(v for v in typevars_map.values()) 

991 

992 if _utils.all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map: 

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

994 _generics.set_cached_generic_type(cls, typevar_values, submodel) 

995 else: 

996 parent_args = cls.__pydantic_generic_metadata__['args'] 

997 if not parent_args: 

998 args = typevar_values 

999 else: 

1000 args = tuple(_generics.replace_types(arg, typevars_map) for arg in parent_args) 

1001 

1002 origin = cls.__pydantic_generic_metadata__['origin'] or cls 

1003 model_name = origin.model_parametrized_name(args) 

1004 params = tuple( 

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

1006 ) # use dict as ordered set 

1007 

1008 with _generics.generic_recursion_self_type(origin, args) as maybe_self_type: 

1009 cached = _generics.get_cached_generic_type_late(cls, typevar_values, origin, args) 

1010 if cached is not None: 

1011 return cached 

1012 

1013 if maybe_self_type is not None: 

1014 return maybe_self_type 

1015 

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

1017 try: 

1018 # depth 2 gets you above this __class_getitem__ call. 

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

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

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

1022 # is being parametrized during a forward annotation evaluation. 

1023 parent_ns = _typing_extra.parent_frame_namespace(parent_depth=2) or {} 

1024 origin.model_rebuild(_types_namespace=parent_ns) 

1025 except PydanticUndefinedAnnotation: 

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

1027 # that could be evaluated later. 

1028 pass 

1029 

1030 submodel = _generics.create_generic_submodel(model_name, origin, args, params) 

1031 

1032 _generics.set_cached_generic_type(cls, typevar_values, submodel, origin, args) 

1033 

1034 return submodel 

1035 

1036 def __copy__(self) -> Self: 

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

1038 cls = type(self) 

1039 m = cls.__new__(cls) 

1040 _object_setattr(m, '__dict__', copy(self.__dict__)) 

1041 _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__)) 

1042 _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) 

1043 

1044 if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: 

1045 _object_setattr(m, '__pydantic_private__', None) 

1046 else: 

1047 _object_setattr( 

1048 m, 

1049 '__pydantic_private__', 

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

1051 ) 

1052 

1053 return m 

1054 

1055 def __deepcopy__(self, memo: Dict[int, Any] | None = None) -> Self: # noqa: UP006 

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

1057 if memo is None: 

1058 memo = {} 

1059 cls = type(self) 

1060 m = cls.__new__(cls) 

1061 memo[id(self)] = m 

1062 _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo)) 

1063 _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo)) 

1064 # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str], 

1065 # and attempting a deepcopy would be marginally slower. 

1066 _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) 

1067 

1068 if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: 

1069 _object_setattr(m, '__pydantic_private__', None) 

1070 else: 

1071 _object_setattr( 

1072 m, 

1073 '__pydantic_private__', 

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

1075 ) 

1076 

1077 return m 

1078 

1079 if not TYPE_CHECKING: 

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

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

1082 

1083 def __getattr__(self, item: str) -> Any: 

1084 private_attributes = object.__getattribute__(self, '__private_attributes__') 

1085 if item in private_attributes: 

1086 attribute = private_attributes[item] 

1087 if hasattr(attribute, '__get__'): 

1088 return attribute.__get__(self, type(self)) # type: ignore 

1089 

1090 try: 

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

1092 return self.__pydantic_private__[item] # type: ignore 

1093 except KeyError as exc: 

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

1095 else: 

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

1097 # See `BaseModel.__repr_args__` for more details 

1098 try: 

1099 pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') 

1100 except AttributeError: 

1101 pydantic_extra = None 

1102 

1103 if pydantic_extra and item in pydantic_extra: 

1104 return pydantic_extra[item] 

1105 else: 

1106 if hasattr(self.__class__, item): 

1107 return super().__getattribute__(item) # Raises AttributeError if appropriate 

1108 else: 

1109 # this is the current error 

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

1111 

1112 def __setattr__(self, name: str, value: Any) -> None: 

1113 if (setattr_handler := self.__pydantic_setattr_handlers__.get(name)) is not None: 

1114 setattr_handler(self, name, value) 

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

1116 elif (setattr_handler := self._setattr_handler(name, value)) is not None: 

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

1118 self.__pydantic_setattr_handlers__[name] = setattr_handler # memoize the handler for faster access 

1119 

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

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

1122 

1123 Returns: 

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

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

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

1127 """ 

1128 cls = self.__class__ 

1129 if name in cls.__class_vars__: 

1130 raise AttributeError( 

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

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

1133 ) 

1134 elif not _fields.is_valid_field_name(name): 

1135 if (attribute := cls.__private_attributes__.get(name)) is not None: 

1136 if hasattr(attribute, '__set__'): 

1137 return lambda model, _name, val: attribute.__set__(model, val) 

1138 else: 

1139 return _SIMPLE_SETATTR_HANDLERS['private'] 

1140 else: 

1141 _object_setattr(self, name, value) 

1142 return None # Can not return memoized handler with possibly freeform attr names 

1143 

1144 attr = getattr(cls, name, _ATTRIBUTE_MISSING) 

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

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

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

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

1149 if isinstance(attr, cached_property): 

1150 return _SIMPLE_SETATTR_HANDLERS['cached_property'] 

1151 

1152 _check_frozen(cls, name, value) 

1153 

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

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

1156 if isinstance(attr, property): 

1157 return lambda model, _name, val: attr.__set__(model, val) 

1158 elif cls.model_config.get('validate_assignment'): 

1159 return _SIMPLE_SETATTR_HANDLERS['validate_assignment'] 

1160 elif name not in cls.__pydantic_fields__: 

1161 if cls.model_config.get('extra') != 'allow': 

1162 # TODO - matching error 

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

1164 elif attr is _ATTRIBUTE_MISSING: 

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

1166 self.__pydantic_extra__[name] = value 

1167 self.__pydantic_fields_set__.add(name) 

1168 return None # Can not return memoized handler with possibly freeform attr names 

1169 else: 

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

1171 return _SIMPLE_SETATTR_HANDLERS['extra_known'] 

1172 else: 

1173 return _SIMPLE_SETATTR_HANDLERS['model_field'] 

1174 

1175 def __delattr__(self, item: str) -> Any: 

1176 cls = self.__class__ 

1177 

1178 if item in self.__private_attributes__: 

1179 attribute = self.__private_attributes__[item] 

1180 if hasattr(attribute, '__delete__'): 

1181 attribute.__delete__(self) # type: ignore 

1182 return 

1183 

1184 try: 

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

1186 del self.__pydantic_private__[item] # type: ignore 

1187 return 

1188 except KeyError as exc: 

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

1190 

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

1192 attr = getattr(cls, item, None) 

1193 if isinstance(attr, cached_property): 

1194 return object.__delattr__(self, item) 

1195 

1196 _check_frozen(cls, name=item, value=None) 

1197 

1198 if item in self.__pydantic_fields__: 

1199 object.__delattr__(self, item) 

1200 elif self.__pydantic_extra__ is not None and item in self.__pydantic_extra__: 

1201 del self.__pydantic_extra__[item] 

1202 else: 

1203 try: 

1204 object.__delattr__(self, item) 

1205 except AttributeError: 

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

1207 

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

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

1210 def __replace__(self, **changes: Any) -> Self: 

1211 return self.model_copy(update=changes) 

1212 

1213 def __getstate__(self) -> Dict[Any, Any]: # noqa: UP006 

1214 private = self.__pydantic_private__ 

1215 if private: 

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

1217 return { 

1218 '__dict__': self.__dict__, 

1219 '__pydantic_extra__': self.__pydantic_extra__, 

1220 '__pydantic_fields_set__': self.__pydantic_fields_set__, 

1221 '__pydantic_private__': private, 

1222 } 

1223 

1224 def __setstate__(self, state: Dict[Any, Any]) -> None: # noqa: UP006 

1225 _object_setattr(self, '__pydantic_fields_set__', state.get('__pydantic_fields_set__', {})) 

1226 _object_setattr(self, '__pydantic_extra__', state.get('__pydantic_extra__', {})) 

1227 _object_setattr(self, '__pydantic_private__', state.get('__pydantic_private__', {})) 

1228 _object_setattr(self, '__dict__', state.get('__dict__', {})) 

1229 

1230 if not TYPE_CHECKING: 

1231 

1232 def __eq__(self, other: Any) -> bool: 

1233 if isinstance(other, BaseModel): 

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

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

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

1237 self_type = self.__pydantic_generic_metadata__['origin'] or self.__class__ 

1238 other_type = other.__pydantic_generic_metadata__['origin'] or other.__class__ 

1239 

1240 # Perform common checks first 

1241 if not ( 

1242 self_type is other_type 

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

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

1245 # can be controlled at validation time: 

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

1247 ): 

1248 return False 

1249 

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

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

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

1253 

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

1255 if self.__dict__ == other.__dict__: 

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

1257 return True 

1258 

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

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

1261 model_fields = type(self).__pydantic_fields__.keys() 

1262 if self.__dict__.keys() <= model_fields and other.__dict__.keys() <= model_fields: 

1263 return False 

1264 

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

1266 # Resort to costly filtering of the __dict__ objects 

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

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

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

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

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

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

1273 try: 

1274 return getter(self.__dict__) == getter(other.__dict__) 

1275 except KeyError: 

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

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

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

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

1280 # in the common case. 

1281 self_fields_proxy = _utils.SafeGetItemProxy(self.__dict__) 

1282 other_fields_proxy = _utils.SafeGetItemProxy(other.__dict__) 

1283 return getter(self_fields_proxy) == getter(other_fields_proxy) 

1284 

1285 # other instance is not a BaseModel 

1286 else: 

1287 return NotImplemented # delegate to the other item in the comparison 

1288 

1289 if TYPE_CHECKING: 

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

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

1292 # subclass initialization. 

1293 

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

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

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

1297 

1298 ```python 

1299 from pydantic import BaseModel 

1300 

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

1302 ``` 

1303 

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

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

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

1307 

1308 Args: 

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

1310 

1311 Note: 

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

1313 *after* the class is fully initialized. 

1314 """ 

1315 

1316 def __iter__(self) -> TupleGenerator: 

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

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

1319 extra = self.__pydantic_extra__ 

1320 if extra: 

1321 yield from extra.items() 

1322 

1323 def __repr__(self) -> str: 

1324 return f'{self.__repr_name__()}({self.__repr_str__(", ")})' 

1325 

1326 def __repr_args__(self) -> _repr.ReprArgs: 

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

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

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

1330 computed_fields_repr_args = [ 

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

1332 ] 

1333 

1334 for k, v in self.__dict__.items(): 

1335 field = self.__pydantic_fields__.get(k) 

1336 if field and field.repr: 

1337 if v is not self: 

1338 yield k, v 

1339 else: 

1340 yield k, self.__repr_recursion__(v) 

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

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

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

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

1345 try: 

1346 pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') 

1347 except AttributeError: 

1348 pydantic_extra = None 

1349 

1350 if pydantic_extra is not None: 

1351 yield from ((k, v) for k, v in pydantic_extra.items()) 

1352 yield from computed_fields_repr_args 

1353 

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

1355 __repr_name__ = _repr.Representation.__repr_name__ 

1356 __repr_recursion__ = _repr.Representation.__repr_recursion__ 

1357 __repr_str__ = _repr.Representation.__repr_str__ 

1358 __pretty__ = _repr.Representation.__pretty__ 

1359 __rich_repr__ = _repr.Representation.__rich_repr__ 

1360 

1361 def __str__(self) -> str: 

1362 return self.__repr_str__(' ') 

1363 

1364 # ##### Deprecated methods from v1 ##### 

1365 @property 

1366 @typing_extensions.deprecated( 

1367 'The `__fields__` attribute is deprecated, use the `model_fields` class property instead.', category=None 

1368 ) 

1369 def __fields__(self) -> Dict[str, FieldInfo]: # noqa: UP006 

1370 warnings.warn( 

1371 'The `__fields__` attribute is deprecated, use the `model_fields` class property instead.', 

1372 category=PydanticDeprecatedSince20, 

1373 stacklevel=2, 

1374 ) 

1375 return getattr(type(self), '__pydantic_fields__', {}) 

1376 

1377 @property 

1378 @typing_extensions.deprecated( 

1379 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.', 

1380 category=None, 

1381 ) 

1382 def __fields_set__(self) -> set[str]: 

1383 warnings.warn( 

1384 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.', 

1385 category=PydanticDeprecatedSince20, 

1386 stacklevel=2, 

1387 ) 

1388 return self.__pydantic_fields_set__ 

1389 

1390 @typing_extensions.deprecated('The `dict` method is deprecated; use `model_dump` instead.', category=None) 

1391 def dict( # noqa: D102 

1392 self, 

1393 *, 

1394 include: IncEx | None = None, 

1395 exclude: IncEx | None = None, 

1396 by_alias: bool = False, 

1397 exclude_unset: bool = False, 

1398 exclude_defaults: bool = False, 

1399 exclude_none: bool = False, 

1400 ) -> Dict[str, Any]: # noqa UP006 

1401 warnings.warn( 

1402 'The `dict` method is deprecated; use `model_dump` instead.', 

1403 category=PydanticDeprecatedSince20, 

1404 stacklevel=2, 

1405 ) 

1406 return self.model_dump( 

1407 include=include, 

1408 exclude=exclude, 

1409 by_alias=by_alias, 

1410 exclude_unset=exclude_unset, 

1411 exclude_defaults=exclude_defaults, 

1412 exclude_none=exclude_none, 

1413 ) 

1414 

1415 @typing_extensions.deprecated('The `json` method is deprecated; use `model_dump_json` instead.', category=None) 

1416 def json( # noqa: D102 

1417 self, 

1418 *, 

1419 include: IncEx | None = None, 

1420 exclude: IncEx | None = None, 

1421 by_alias: bool = False, 

1422 exclude_unset: bool = False, 

1423 exclude_defaults: bool = False, 

1424 exclude_none: bool = False, 

1425 encoder: Callable[[Any], Any] | None = PydanticUndefined, # type: ignore[assignment] 

1426 models_as_dict: bool = PydanticUndefined, # type: ignore[assignment] 

1427 **dumps_kwargs: Any, 

1428 ) -> str: 

1429 warnings.warn( 

1430 'The `json` method is deprecated; use `model_dump_json` instead.', 

1431 category=PydanticDeprecatedSince20, 

1432 stacklevel=2, 

1433 ) 

1434 if encoder is not PydanticUndefined: 

1435 raise TypeError('The `encoder` argument is no longer supported; use field serializers instead.') 

1436 if models_as_dict is not PydanticUndefined: 

1437 raise TypeError('The `models_as_dict` argument is no longer supported; use a model serializer instead.') 

1438 if dumps_kwargs: 

1439 raise TypeError('`dumps_kwargs` keyword arguments are no longer supported.') 

1440 return self.model_dump_json( 

1441 include=include, 

1442 exclude=exclude, 

1443 by_alias=by_alias, 

1444 exclude_unset=exclude_unset, 

1445 exclude_defaults=exclude_defaults, 

1446 exclude_none=exclude_none, 

1447 ) 

1448 

1449 @classmethod 

1450 @typing_extensions.deprecated('The `parse_obj` method is deprecated; use `model_validate` instead.', category=None) 

1451 def parse_obj(cls, obj: Any) -> Self: # noqa: D102 

1452 warnings.warn( 

1453 'The `parse_obj` method is deprecated; use `model_validate` instead.', 

1454 category=PydanticDeprecatedSince20, 

1455 stacklevel=2, 

1456 ) 

1457 return cls.model_validate(obj) 

1458 

1459 @classmethod 

1460 @typing_extensions.deprecated( 

1461 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ' 

1462 'otherwise load the data then use `model_validate` instead.', 

1463 category=None, 

1464 ) 

1465 def parse_raw( # noqa: D102 

1466 cls, 

1467 b: str | bytes, 

1468 *, 

1469 content_type: str | None = None, 

1470 encoding: str = 'utf8', 

1471 proto: DeprecatedParseProtocol | None = None, 

1472 allow_pickle: bool = False, 

1473 ) -> Self: # pragma: no cover 

1474 warnings.warn( 

1475 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ' 

1476 'otherwise load the data then use `model_validate` instead.', 

1477 category=PydanticDeprecatedSince20, 

1478 stacklevel=2, 

1479 ) 

1480 from .deprecated import parse 

1481 

1482 try: 

1483 obj = parse.load_str_bytes( 

1484 b, 

1485 proto=proto, 

1486 content_type=content_type, 

1487 encoding=encoding, 

1488 allow_pickle=allow_pickle, 

1489 ) 

1490 except (ValueError, TypeError) as exc: 

1491 import json 

1492 

1493 # try to match V1 

1494 if isinstance(exc, UnicodeDecodeError): 

1495 type_str = 'value_error.unicodedecode' 

1496 elif isinstance(exc, json.JSONDecodeError): 

1497 type_str = 'value_error.jsondecode' 

1498 elif isinstance(exc, ValueError): 

1499 type_str = 'value_error' 

1500 else: 

1501 type_str = 'type_error' 

1502 

1503 # ctx is missing here, but since we've added `input` to the error, we're not pretending it's the same 

1504 error: pydantic_core.InitErrorDetails = { 

1505 # The type: ignore on the next line is to ignore the requirement of LiteralString 

1506 'type': pydantic_core.PydanticCustomError(type_str, str(exc)), # type: ignore 

1507 'loc': ('__root__',), 

1508 'input': b, 

1509 } 

1510 raise pydantic_core.ValidationError.from_exception_data(cls.__name__, [error]) 

1511 return cls.model_validate(obj) 

1512 

1513 @classmethod 

1514 @typing_extensions.deprecated( 

1515 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON ' 

1516 'use `model_validate_json`, otherwise `model_validate` instead.', 

1517 category=None, 

1518 ) 

1519 def parse_file( # noqa: D102 

1520 cls, 

1521 path: str | Path, 

1522 *, 

1523 content_type: str | None = None, 

1524 encoding: str = 'utf8', 

1525 proto: DeprecatedParseProtocol | None = None, 

1526 allow_pickle: bool = False, 

1527 ) -> Self: 

1528 warnings.warn( 

1529 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON ' 

1530 'use `model_validate_json`, otherwise `model_validate` instead.', 

1531 category=PydanticDeprecatedSince20, 

1532 stacklevel=2, 

1533 ) 

1534 from .deprecated import parse 

1535 

1536 obj = parse.load_file( 

1537 path, 

1538 proto=proto, 

1539 content_type=content_type, 

1540 encoding=encoding, 

1541 allow_pickle=allow_pickle, 

1542 ) 

1543 return cls.parse_obj(obj) 

1544 

1545 @classmethod 

1546 @typing_extensions.deprecated( 

1547 'The `from_orm` method is deprecated; set ' 

1548 "`model_config['from_attributes']=True` and use `model_validate` instead.", 

1549 category=None, 

1550 ) 

1551 def from_orm(cls, obj: Any) -> Self: # noqa: D102 

1552 warnings.warn( 

1553 'The `from_orm` method is deprecated; set ' 

1554 "`model_config['from_attributes']=True` and use `model_validate` instead.", 

1555 category=PydanticDeprecatedSince20, 

1556 stacklevel=2, 

1557 ) 

1558 if not cls.model_config.get('from_attributes', None): 

1559 raise PydanticUserError( 

1560 'You must set the config attribute `from_attributes=True` to use from_orm', code=None 

1561 ) 

1562 return cls.model_validate(obj) 

1563 

1564 @classmethod 

1565 @typing_extensions.deprecated('The `construct` method is deprecated; use `model_construct` instead.', category=None) 

1566 def construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self: # noqa: D102 

1567 warnings.warn( 

1568 'The `construct` method is deprecated; use `model_construct` instead.', 

1569 category=PydanticDeprecatedSince20, 

1570 stacklevel=2, 

1571 ) 

1572 return cls.model_construct(_fields_set=_fields_set, **values) 

1573 

1574 @typing_extensions.deprecated( 

1575 'The `copy` method is deprecated; use `model_copy` instead. ' 

1576 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.', 

1577 category=None, 

1578 ) 

1579 def copy( 

1580 self, 

1581 *, 

1582 include: AbstractSetIntStr | MappingIntStrAny | None = None, 

1583 exclude: AbstractSetIntStr | MappingIntStrAny | None = None, 

1584 update: Dict[str, Any] | None = None, # noqa UP006 

1585 deep: bool = False, 

1586 ) -> Self: # pragma: no cover 

1587 """Returns a copy of the model. 

1588 

1589 !!! warning "Deprecated" 

1590 This method is now deprecated; use `model_copy` instead. 

1591 

1592 If you need `include` or `exclude`, use: 

1593 

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

1595 data = self.model_dump(include=include, exclude=exclude, round_trip=True) 

1596 data = {**data, **(update or {})} 

1597 copied = self.model_validate(data) 

1598 ``` 

1599 

1600 Args: 

1601 include: Optional set or mapping specifying which fields to include in the copied model. 

1602 exclude: Optional set or mapping specifying which fields to exclude in the copied model. 

1603 update: Optional dictionary of field-value pairs to override field values in the copied model. 

1604 deep: If True, the values of fields that are Pydantic models will be deep-copied. 

1605 

1606 Returns: 

1607 A copy of the model with included, excluded and updated fields as specified. 

1608 """ 

1609 warnings.warn( 

1610 'The `copy` method is deprecated; use `model_copy` instead. ' 

1611 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.', 

1612 category=PydanticDeprecatedSince20, 

1613 stacklevel=2, 

1614 ) 

1615 from .deprecated import copy_internals 

1616 

1617 values = dict( 

1618 copy_internals._iter( 

1619 self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False 

1620 ), 

1621 **(update or {}), 

1622 ) 

1623 if self.__pydantic_private__ is None: 

1624 private = None 

1625 else: 

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

1627 

1628 if self.__pydantic_extra__ is None: 

1629 extra: dict[str, Any] | None = None 

1630 else: 

1631 extra = self.__pydantic_extra__.copy() 

1632 for k in list(self.__pydantic_extra__): 

1633 if k not in values: # k was in the exclude 

1634 extra.pop(k) 

1635 for k in list(values): 

1636 if k in self.__pydantic_extra__: # k must have come from extra 

1637 extra[k] = values.pop(k) 

1638 

1639 # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg 

1640 if update: 

1641 fields_set = self.__pydantic_fields_set__ | update.keys() 

1642 else: 

1643 fields_set = set(self.__pydantic_fields_set__) 

1644 

1645 # removing excluded fields from `__pydantic_fields_set__` 

1646 if exclude: 

1647 fields_set -= set(exclude) 

1648 

1649 return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep) 

1650 

1651 @classmethod 

1652 @typing_extensions.deprecated('The `schema` method is deprecated; use `model_json_schema` instead.', category=None) 

1653 def schema( # noqa: D102 

1654 cls, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE 

1655 ) -> Dict[str, Any]: # noqa UP006 

1656 warnings.warn( 

1657 'The `schema` method is deprecated; use `model_json_schema` instead.', 

1658 category=PydanticDeprecatedSince20, 

1659 stacklevel=2, 

1660 ) 

1661 return cls.model_json_schema(by_alias=by_alias, ref_template=ref_template) 

1662 

1663 @classmethod 

1664 @typing_extensions.deprecated( 

1665 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.', 

1666 category=None, 

1667 ) 

1668 def schema_json( # noqa: D102 

1669 cls, *, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, **dumps_kwargs: Any 

1670 ) -> str: # pragma: no cover 

1671 warnings.warn( 

1672 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.', 

1673 category=PydanticDeprecatedSince20, 

1674 stacklevel=2, 

1675 ) 

1676 import json 

1677 

1678 from .deprecated.json import pydantic_encoder 

1679 

1680 return json.dumps( 

1681 cls.model_json_schema(by_alias=by_alias, ref_template=ref_template), 

1682 default=pydantic_encoder, 

1683 **dumps_kwargs, 

1684 ) 

1685 

1686 @classmethod 

1687 @typing_extensions.deprecated('The `validate` method is deprecated; use `model_validate` instead.', category=None) 

1688 def validate(cls, value: Any) -> Self: # noqa: D102 

1689 warnings.warn( 

1690 'The `validate` method is deprecated; use `model_validate` instead.', 

1691 category=PydanticDeprecatedSince20, 

1692 stacklevel=2, 

1693 ) 

1694 return cls.model_validate(value) 

1695 

1696 @classmethod 

1697 @typing_extensions.deprecated( 

1698 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.', 

1699 category=None, 

1700 ) 

1701 def update_forward_refs(cls, **localns: Any) -> None: # noqa: D102 

1702 warnings.warn( 

1703 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.', 

1704 category=PydanticDeprecatedSince20, 

1705 stacklevel=2, 

1706 ) 

1707 if localns: # pragma: no cover 

1708 raise TypeError('`localns` arguments are not longer accepted.') 

1709 cls.model_rebuild(force=True) 

1710 

1711 @typing_extensions.deprecated( 

1712 'The private method `_iter` will be removed and should no longer be used.', category=None 

1713 ) 

1714 def _iter(self, *args: Any, **kwargs: Any) -> Any: 

1715 warnings.warn( 

1716 'The private method `_iter` will be removed and should no longer be used.', 

1717 category=PydanticDeprecatedSince20, 

1718 stacklevel=2, 

1719 ) 

1720 from .deprecated import copy_internals 

1721 

1722 return copy_internals._iter(self, *args, **kwargs) 

1723 

1724 @typing_extensions.deprecated( 

1725 'The private method `_copy_and_set_values` will be removed and should no longer be used.', 

1726 category=None, 

1727 ) 

1728 def _copy_and_set_values(self, *args: Any, **kwargs: Any) -> Any: 

1729 warnings.warn( 

1730 'The private method `_copy_and_set_values` will be removed and should no longer be used.', 

1731 category=PydanticDeprecatedSince20, 

1732 stacklevel=2, 

1733 ) 

1734 from .deprecated import copy_internals 

1735 

1736 return copy_internals._copy_and_set_values(self, *args, **kwargs) 

1737 

1738 @classmethod 

1739 @typing_extensions.deprecated( 

1740 'The private method `_get_value` will be removed and should no longer be used.', 

1741 category=None, 

1742 ) 

1743 def _get_value(cls, *args: Any, **kwargs: Any) -> Any: 

1744 warnings.warn( 

1745 'The private method `_get_value` will be removed and should no longer be used.', 

1746 category=PydanticDeprecatedSince20, 

1747 stacklevel=2, 

1748 ) 

1749 from .deprecated import copy_internals 

1750 

1751 return copy_internals._get_value(cls, *args, **kwargs) 

1752 

1753 @typing_extensions.deprecated( 

1754 'The private method `_calculate_keys` will be removed and should no longer be used.', 

1755 category=None, 

1756 ) 

1757 def _calculate_keys(self, *args: Any, **kwargs: Any) -> Any: 

1758 warnings.warn( 

1759 'The private method `_calculate_keys` will be removed and should no longer be used.', 

1760 category=PydanticDeprecatedSince20, 

1761 stacklevel=2, 

1762 ) 

1763 from .deprecated import copy_internals 

1764 

1765 return copy_internals._calculate_keys(self, *args, **kwargs) 

1766 

1767 

1768ModelT = TypeVar('ModelT', bound=BaseModel) 

1769 

1770_CREATE_MODEL_RESERVED_NAMESPACE_KEYS: dict[str, str] = { 

1771 '__annotations__': 'field definitions', 

1772 '__module__': 'the `__module__` argument', 

1773 '__qualname__': 'the `__qualname__` argument', 

1774 '__doc__': 'the `__doc__` argument', 

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

1776} 

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

1778 

1779 

1780@overload 

1781def create_model( 

1782 model_name: str, 

1783 /, 

1784 *, 

1785 __config__: ConfigDict | None = None, 

1786 __doc__: str | None = None, 

1787 __base__: None = None, 

1788 __module__: str = __name__, 

1789 __validators__: dict[str, Callable[..., Any]] | None = None, 

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

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

1792 __qualname__: str | None = None, 

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

1794) -> type[BaseModel]: ... 

1795 

1796 

1797@overload 

1798def create_model( 

1799 model_name: str, 

1800 /, 

1801 *, 

1802 __config__: ConfigDict | None = None, 

1803 __doc__: str | None = None, 

1804 __base__: type[ModelT] | tuple[type[ModelT], ...], 

1805 __module__: str = __name__, 

1806 __validators__: dict[str, Callable[..., Any]] | None = None, 

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

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

1809 __qualname__: str | None = None, 

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

1811) -> type[ModelT]: ... 

1812 

1813 

1814def create_model( # noqa: C901 

1815 model_name: str, 

1816 /, 

1817 *, 

1818 __config__: ConfigDict | None = None, 

1819 __doc__: str | None = None, 

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

1821 __module__: str | None = None, 

1822 __validators__: dict[str, Callable[..., Any]] | None = None, 

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

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

1825 __qualname__: str | None = None, 

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

1827) -> type[ModelT]: 

1828 """!!! abstract "Usage Documentation" 

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

1830 

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

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

1833 

1834 !!! warning 

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

1836 

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

1838 

1839 Args: 

1840 model_name: The name of the newly created model. 

1841 __config__: The configuration of the new model. 

1842 __doc__: The docstring of the new model. 

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

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

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

1846 __validators__: A dictionary of methods that validate fields. The keys are the names of the validation methods to 

1847 be added to the model, and the values are the validation methods themselves. You can read more about functional 

1848 validators [here](../concepts/validators.md#field-validators). 

1849 

1850 /// version-changed | v2.14 

1851 It is now recommended to use the `__namespace__` argument, which isn't restricted to validators. 

1852 `__validators__` will be deprecated in v3. 

1853 /// 

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

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

1856 Keys take precedence over the ones from `__validators__`, and must not clash with any of the field names 

1857 or with the attributes that have a dedicated argument (`__annotations__`, `__module__`, `__qualname__`, 

1858 `__doc__` and `model_config`). 

1859 

1860 /// version-added | v2.14 

1861 This argument replaces `__validators__`, which will be deprecated in v3. 

1862 /// 

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

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

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

1866 

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

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

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

1870 

1871 Returns: 

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

1873 

1874 Raises: 

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

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

1877 """ 

1878 if __base__ is None: 

1879 __base__ = (cast('type[ModelT]', BaseModel),) 

1880 elif not isinstance(__base__, tuple): 

1881 __base__ = (__base__,) 

1882 

1883 __cls_kwargs__ = __cls_kwargs__ or {} 

1884 

1885 fields: dict[str, Any] = {} 

1886 annotations: dict[str, Any] = {} 

1887 

1888 for f_name, f_def in field_definitions.items(): 

1889 if isinstance(f_def, tuple): 

1890 if len(f_def) != 2: 

1891 raise PydanticUserError( 

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

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

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

1895 ) 

1896 

1897 annotations[f_name] = f_def[0] 

1898 fields[f_name] = f_def[1] 

1899 else: 

1900 annotations[f_name] = f_def 

1901 

1902 if __namespace__: 

1903 if clashing_names := field_definitions.keys() & __namespace__.keys(): 

1904 raise PydanticUserError( 

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

1906 code='create-model-namespace', 

1907 ) 

1908 for key, argument in _CREATE_MODEL_RESERVED_NAMESPACE_KEYS.items(): 

1909 if key in __namespace__: 

1910 raise PydanticUserError( 

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

1912 code='create-model-namespace', 

1913 ) 

1914 

1915 if __module__ is None: 

1916 f = sys._getframe(1) 

1917 __module__ = f.f_globals['__name__'] 

1918 

1919 namespace: dict[str, Any] = {'__annotations__': annotations, '__module__': __module__} 

1920 if __doc__: 

1921 namespace['__doc__'] = __doc__ 

1922 if __qualname__ is not None: 

1923 namespace['__qualname__'] = __qualname__ 

1924 if __validators__: 

1925 namespace.update(__validators__) 

1926 if __namespace__: 

1927 namespace.update(__namespace__) 

1928 namespace.update(fields) 

1929 if __config__: 

1930 namespace['model_config'] = __config__ 

1931 resolved_bases = types.resolve_bases(__base__) 

1932 meta, ns, kwds = types.prepare_class(model_name, resolved_bases, kwds=__cls_kwargs__) 

1933 if resolved_bases is not __base__: 

1934 ns['__orig_bases__'] = __base__ 

1935 namespace.update(ns) 

1936 

1937 return meta( 

1938 model_name, 

1939 resolved_bases, 

1940 namespace, 

1941 __pydantic_reset_parent_namespace__=False, 

1942 _create_model_module=__module__, 

1943 **kwds, 

1944 ) 

1945 

1946 

1947__getattr__ = getattr_migration(__name__)