Movatterモバイル変換


[0]ホーム

URL:


Skip to content
What's new — we've launchedPydantic Logfire🔥to help you monitor and understand yourPydantic validations.

BaseModel

Pydantic models are simply classes which inherit fromBaseModel and define fields as annotated attributes.

pydantic.BaseModel

Usage Documentation

Models

A base class for creating Pydantic models.

Attributes:

NameTypeDescription
__class_vars__set[str]

The names of the class variables defined on the model.

__private_attributes__Dict[str,ModelPrivateAttr]

Metadata about the private attributes of the model.

__signature__Signature

The synthesized__init__Signature of the model.

__pydantic_complete__bool

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

__pydantic_core_schema__CoreSchema

The core schema of the model.

__pydantic_custom_init__bool

Whether the model has a custom__init__ function.

__pydantic_decorators__DecoratorInfos

Metadata containing the decorators defined on the model.This replacesModel.__validators__ andModel.__root_validators__ from Pydantic V1.

__pydantic_generic_metadata__PydanticGenericMetadata

Metadata for generic models; contains data used for a similar purpose toargs,origin,parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__Dict[str,Any] | None

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

__pydantic_post_init__None |Literal['model_post_init']

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

__pydantic_root_model__bool

Whether the model is aRootModel.

__pydantic_serializer__SchemaSerializer

Thepydantic-coreSchemaSerializer used to dump instances of the model.

__pydantic_validator__SchemaValidator |PluggableSchemaValidator

Thepydantic-coreSchemaValidator used to validate instances of the model.

__pydantic_fields__Dict[str,FieldInfo]

A dictionary of field names and their correspondingFieldInfo objects.

__pydantic_computed_fields__Dict[str,ComputedFieldInfo]

A dictionary of computed field names and their correspondingComputedFieldInfo objects.

__pydantic_extra__dict[str,Any] | None

A dictionary containing extra values, ifextrais set to'allow'.

__pydantic_fields_set__set[str]

The names of fields explicitly set during instantiation.

__pydantic_private__dict[str,Any] | None

Values of private attributes set on the model instance.

Source code inpydantic/main.py
 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 99910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643
classBaseModel(metaclass=_model_construction.ModelMetaclass):"""!!! abstract "Usage Documentation"        [Models](../concepts/models.md)    A base class for creating Pydantic models.    Attributes:        __class_vars__: The names of the class variables defined on the model.        __private_attributes__: Metadata about the private attributes of the model.        __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model.        __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.        __pydantic_core_schema__: The core schema of the model.        __pydantic_custom_init__: Whether the model has a custom `__init__` function.        __pydantic_decorators__: Metadata containing the decorators defined on the model.            This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.        __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to            __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.        __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.        __pydantic_post_init__: The name of the post-init method for the model, if defined.        __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].        __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.        __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.        __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.        __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.        __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]            is set to `'allow'`.        __pydantic_fields_set__: The names of fields explicitly set during instantiation.        __pydantic_private__: Values of private attributes set on the model instance.    """# Note: Many of the below class vars are defined in the metaclass, but we define them here for type checking purposes.model_config:ClassVar[ConfigDict]=ConfigDict()"""    Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict].    """__class_vars__:ClassVar[set[str]]"""The names of the class variables defined on the model."""__private_attributes__:ClassVar[Dict[str,ModelPrivateAttr]]# noqa: UP006"""Metadata about the private attributes of the model."""__signature__:ClassVar[Signature]"""The synthesized `__init__` [`Signature`][inspect.Signature] of the model."""__pydantic_complete__:ClassVar[bool]=False"""Whether model building is completed, or if there are still undefined fields."""__pydantic_core_schema__:ClassVar[CoreSchema]"""The core schema of the model."""__pydantic_custom_init__:ClassVar[bool]"""Whether the model has a custom `__init__` method."""# Must be set for `GenerateSchema.model_schema` to work for a plain `BaseModel` annotation.__pydantic_decorators__:ClassVar[_decorators.DecoratorInfos]=_decorators.DecoratorInfos()"""Metadata containing the decorators defined on the model.    This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1."""__pydantic_generic_metadata__:ClassVar[_generics.PydanticGenericMetadata]"""Metadata for generic models; contains data used for a similar purpose to    __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these."""__pydantic_parent_namespace__:ClassVar[Dict[str,Any]|None]=None# noqa: UP006"""Parent namespace of the model, used for automatic rebuilding of models."""__pydantic_post_init__:ClassVar[None|Literal['model_post_init']]"""The name of the post-init method for the model, if defined."""__pydantic_root_model__:ClassVar[bool]=False"""Whether the model is a [`RootModel`][pydantic.root_model.RootModel]."""__pydantic_serializer__:ClassVar[SchemaSerializer]"""The `pydantic-core` `SchemaSerializer` used to dump instances of the model."""__pydantic_validator__:ClassVar[SchemaValidator|PluggableSchemaValidator]"""The `pydantic-core` `SchemaValidator` used to validate instances of the model."""__pydantic_fields__:ClassVar[Dict[str,FieldInfo]]# noqa: UP006"""A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.    This replaces `Model.__fields__` from Pydantic V1.    """__pydantic_setattr_handlers__:ClassVar[Dict[str,Callable[[BaseModel,str,Any],None]]]# noqa: UP006"""`__setattr__` handlers. Memoizing the handlers leads to a dramatic performance improvement in `__setattr__`"""__pydantic_computed_fields__:ClassVar[Dict[str,ComputedFieldInfo]]# noqa: UP006"""A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects."""__pydantic_extra__:dict[str,Any]|None=_model_construction.NoInitField(init=False)"""A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] is set to `'allow'`."""__pydantic_fields_set__:set[str]=_model_construction.NoInitField(init=False)"""The names of fields explicitly set during instantiation."""__pydantic_private__:dict[str,Any]|None=_model_construction.NoInitField(init=False)"""Values of private attributes set on the model instance."""ifnotTYPE_CHECKING:# Prevent `BaseModel` from being instantiated directly# (defined in an `if not TYPE_CHECKING` block for clarity and to avoid type checking errors):__pydantic_core_schema__=_mock_val_ser.MockCoreSchema('Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',code='base-model-instantiated',)__pydantic_validator__=_mock_val_ser.MockValSer('Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',val_or_ser='validator',code='base-model-instantiated',)__pydantic_serializer__=_mock_val_ser.MockValSer('Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',val_or_ser='serializer',code='base-model-instantiated',)__slots__='__dict__','__pydantic_fields_set__','__pydantic_extra__','__pydantic_private__'def__init__(self,/,**data:Any)->None:"""Create a new model by parsing and validating input data from keyword arguments.        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be        validated to form a valid model.        `self` is explicitly positional-only to allow `self` as a field name.        """# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks__tracebackhide__=Truevalidated_self=self.__pydantic_validator__.validate_python(data,self_instance=self)ifselfisnotvalidated_self:warnings.warn('A custom validator is returning a value other than `self`.\n'"Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',stacklevel=2,)# The following line sets a flag that we use to determine when `__init__` gets overridden by the user__init__.__pydantic_base_init__=True# pyright: ignore[reportFunctionMemberAccess]@_utils.deprecated_instance_property@classmethoddefmodel_fields(cls)->dict[str,FieldInfo]:"""A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.        !!! warning            Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.            Instead, you should access this attribute from the model class.        """returngetattr(cls,'__pydantic_fields__',{})@_utils.deprecated_instance_property@classmethoddefmodel_computed_fields(cls)->dict[str,ComputedFieldInfo]:"""A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.        !!! warning            Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.            Instead, you should access this attribute from the model class.        """returngetattr(cls,'__pydantic_computed_fields__',{})@propertydefmodel_extra(self)->dict[str,Any]|None:"""Get extra fields set during validation.        Returns:            A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.        """returnself.__pydantic_extra__@propertydefmodel_fields_set(self)->set[str]:"""Returns the set of fields that have been explicitly set on this model instance.        Returns:            A set of strings representing the fields that have been set,                i.e. that were not filled from defaults.        """returnself.__pydantic_fields_set__@classmethoddefmodel_construct(cls,_fields_set:set[str]|None=None,**values:Any)->Self:# noqa: C901"""Creates a new instance of the `Model` class with validated data.        Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.        Default values are respected, but no other validation is performed.        !!! note            `model_construct()` generally respects the `model_config.extra` setting on the provided model.            That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`            and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.            Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in            an error if extra values are passed, but they will be ignored.        Args:            _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,                this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.                Otherwise, the field names from the `values` argument will be used.            values: Trusted or pre-validated data dictionary.        Returns:            A new instance of the `Model` class with validated data.        """m=cls.__new__(cls)fields_values:dict[str,Any]={}fields_set=set()forname,fieldincls.__pydantic_fields__.items():iffield.aliasisnotNoneandfield.aliasinvalues:fields_values[name]=values.pop(field.alias)fields_set.add(name)if(namenotinfields_set)and(field.validation_aliasisnotNone):validation_aliases:list[str|AliasPath]=(field.validation_alias.choicesifisinstance(field.validation_alias,AliasChoices)else[field.validation_alias])foraliasinvalidation_aliases:ifisinstance(alias,str)andaliasinvalues:fields_values[name]=values.pop(alias)fields_set.add(name)breakelifisinstance(alias,AliasPath):value=alias.search_dict_for_path(values)ifvalueisnotPydanticUndefined:fields_values[name]=valuefields_set.add(name)breakifnamenotinfields_set:ifnameinvalues:fields_values[name]=values.pop(name)fields_set.add(name)elifnotfield.is_required():fields_values[name]=field.get_default(call_default_factory=True,validated_data=fields_values)if_fields_setisNone:_fields_set=fields_set_extra:dict[str,Any]|None=valuesifcls.model_config.get('extra')=='allow'elseNone_object_setattr(m,'__dict__',fields_values)_object_setattr(m,'__pydantic_fields_set__',_fields_set)ifnotcls.__pydantic_root_model__:_object_setattr(m,'__pydantic_extra__',_extra)ifcls.__pydantic_post_init__:m.model_post_init(None)# update private attributes with values setifhasattr(m,'__pydantic_private__')andm.__pydantic_private__isnotNone:fork,vinvalues.items():ifkinm.__private_attributes__:m.__pydantic_private__[k]=velifnotcls.__pydantic_root_model__:# Note: if there are any private attributes, cls.__pydantic_post_init__ would exist# Since it doesn't, that means that `__pydantic_private__` should be set to None_object_setattr(m,'__pydantic_private__',None)returnmdefmodel_copy(self,*,update:Mapping[str,Any]|None=None,deep:bool=False)->Self:"""!!! abstract "Usage Documentation"            [`model_copy`](../concepts/serialization.md#model_copy)        Returns a copy of the model.        !!! note            The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This            might have unexpected side effects if you store anything in it, on top of the model            fields (e.g. the value of [cached properties][functools.cached_property]).        Args:            update: Values to change/add in the new model. Note: the data is not validated                before creating the new model. You should trust this data.            deep: Set to `True` to make a deep copy of the model.        Returns:            New model instance.        """copied=self.__deepcopy__()ifdeepelseself.__copy__()ifupdate:ifself.model_config.get('extra')=='allow':fork,vinupdate.items():ifkinself.__pydantic_fields__:copied.__dict__[k]=velse:ifcopied.__pydantic_extra__isNone:copied.__pydantic_extra__={}copied.__pydantic_extra__[k]=velse:copied.__dict__.update(update)copied.__pydantic_fields_set__.update(update.keys())returncopieddefmodel_dump(self,*,mode:Literal['json','python']|str='python',include:IncEx|None=None,exclude:IncEx|None=None,context:Any|None=None,by_alias:bool|None=None,exclude_unset:bool=False,exclude_defaults:bool=False,exclude_none:bool=False,round_trip:bool=False,warnings:bool|Literal['none','warn','error']=True,fallback:Callable[[Any],Any]|None=None,serialize_as_any:bool=False,)->dict[str,Any]:"""!!! abstract "Usage Documentation"            [`model_dump`](../concepts/serialization.md#modelmodel_dump)        Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.        Args:            mode: The mode in which `to_python` should run.                If mode is 'json', the output will only contain JSON serializable types.                If mode is 'python', the output may contain non-JSON-serializable Python objects.            include: A set of fields to include in the output.            exclude: A set of fields to exclude from the output.            context: Additional context to pass to the serializer.            by_alias: Whether to use the field's alias in the dictionary key if defined.            exclude_unset: Whether to exclude fields that have not been explicitly set.            exclude_defaults: Whether to exclude fields that are set to their default value.            exclude_none: Whether to exclude fields that have a value of `None`.            round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].            warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].            fallback: A function to call when an unknown value is encountered. If not provided,                a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.        Returns:            A dictionary representation of the model.        """returnself.__pydantic_serializer__.to_python(self,mode=mode,by_alias=by_alias,include=include,exclude=exclude,context=context,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,round_trip=round_trip,warnings=warnings,fallback=fallback,serialize_as_any=serialize_as_any,)defmodel_dump_json(self,*,indent:int|None=None,include:IncEx|None=None,exclude:IncEx|None=None,context:Any|None=None,by_alias:bool|None=None,exclude_unset:bool=False,exclude_defaults:bool=False,exclude_none:bool=False,round_trip:bool=False,warnings:bool|Literal['none','warn','error']=True,fallback:Callable[[Any],Any]|None=None,serialize_as_any:bool=False,)->str:"""!!! abstract "Usage Documentation"            [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json)        Generates a JSON representation of the model using Pydantic's `to_json` method.        Args:            indent: Indentation to use in the JSON output. If None is passed, the output will be compact.            include: Field(s) to include in the JSON output.            exclude: Field(s) to exclude from the JSON output.            context: Additional context to pass to the serializer.            by_alias: Whether to serialize using field aliases.            exclude_unset: Whether to exclude fields that have not been explicitly set.            exclude_defaults: Whether to exclude fields that are set to their default value.            exclude_none: Whether to exclude fields that have a value of `None`.            round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].            warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].            fallback: A function to call when an unknown value is encountered. If not provided,                a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.        Returns:            A JSON string representation of the model.        """returnself.__pydantic_serializer__.to_json(self,indent=indent,include=include,exclude=exclude,context=context,by_alias=by_alias,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,round_trip=round_trip,warnings=warnings,fallback=fallback,serialize_as_any=serialize_as_any,).decode()@classmethoddefmodel_json_schema(cls,by_alias:bool=True,ref_template:str=DEFAULT_REF_TEMPLATE,schema_generator:type[GenerateJsonSchema]=GenerateJsonSchema,mode:JsonSchemaMode='validation',)->dict[str,Any]:"""Generates a JSON schema for a model class.        Args:            by_alias: Whether to use attribute aliases or not.            ref_template: The reference template.            schema_generator: To override the logic used to generate the JSON schema, as a subclass of                `GenerateJsonSchema` with your desired modifications            mode: The mode in which to generate the schema.        Returns:            The JSON schema for the given model class.        """returnmodel_json_schema(cls,by_alias=by_alias,ref_template=ref_template,schema_generator=schema_generator,mode=mode)@classmethoddefmodel_parametrized_name(cls,params:tuple[type[Any],...])->str:"""Compute the class name for parametrizations of generic classes.        This method can be overridden to achieve a custom naming scheme for generic BaseModels.        Args:            params: Tuple of types of the class. Given a generic class                `Model` with 2 type variables and a concrete model `Model[str, int]`,                the value `(str, int)` would be passed to `params`.        Returns:            String representing the new class where `params` are passed to `cls` as type variables.        Raises:            TypeError: Raised when trying to generate concrete names for non-generic models.        """ifnotissubclass(cls,typing.Generic):raiseTypeError('Concrete names should only be generated for generic models.')# Any strings received should represent forward references, so we handle them specially below.# If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,# we may be able to remove this special case.param_names=[paramifisinstance(param,str)else_repr.display_as_type(param)forparaminparams]params_component=', '.join(param_names)returnf'{cls.__name__}[{params_component}]'defmodel_post_init(self,context:Any,/)->None:"""Override this method to perform additional initialization after `__init__` and `model_construct`.        This is useful if you want to do some validation that requires the entire model to be initialized.        """pass@classmethoddefmodel_rebuild(cls,*,force:bool=False,raise_errors:bool=True,_parent_namespace_depth:int=2,_types_namespace:MappingNamespace|None=None,)->bool|None:"""Try to rebuild the pydantic-core schema for the model.        This may be necessary when one of the annotations is a ForwardRef which could not be resolved during        the initial attempt to build the schema, and automatic rebuilding fails.        Args:            force: Whether to force the rebuilding of the model schema, defaults to `False`.            raise_errors: Whether to raise errors, defaults to `True`.            _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.            _types_namespace: The types namespace, defaults to `None`.        Returns:            Returns `None` if the schema is already "complete" and rebuilding was not required.            If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.        """ifnotforceandcls.__pydantic_complete__:returnNoneforattrin('__pydantic_core_schema__','__pydantic_validator__','__pydantic_serializer__'):ifattrincls.__dict__andnotisinstance(getattr(cls,attr),_mock_val_ser.MockValSer):# Deleting the validator/serializer is necessary as otherwise they can get reused in# pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`# isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.# Same applies for the core schema that can be reused in schema generation.delattr(cls,attr)cls.__pydantic_complete__=Falseif_types_namespaceisnotNone:rebuild_ns=_types_namespaceelif_parent_namespace_depth>0:rebuild_ns=_typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth,force=True)or{}else:rebuild_ns={}parent_ns=_model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__)or{}ns_resolver=_namespace_utils.NsResolver(parent_namespace={**rebuild_ns,**parent_ns},)ifnotcls.__pydantic_fields_complete__:typevars_map=_generics.get_model_typevars_map(cls)try:cls.__pydantic_fields__=_fields.rebuild_model_fields(cls,ns_resolver=ns_resolver,typevars_map=typevars_map,)exceptNameErrorase:exc=PydanticUndefinedAnnotation.from_name_error(e)_mock_val_ser.set_model_mocks(cls,f'`{exc.name}`')ifraise_errors:raiseexcfromeifnotraise_errorsandnotcls.__pydantic_fields_complete__:# No need to continue with schema gen, it is guaranteed to failreturnFalseassertcls.__pydantic_fields_complete__return_model_construction.complete_model_class(cls,_config.ConfigWrapper(cls.model_config,check=False),raise_errors=raise_errors,ns_resolver=ns_resolver,)@classmethoddefmodel_validate(cls,obj:Any,*,strict:bool|None=None,from_attributes:bool|None=None,context:Any|None=None,by_alias:bool|None=None,by_name:bool|None=None,)->Self:"""Validate a pydantic model instance.        Args:            obj: The object to validate.            strict: Whether to enforce types strictly.            from_attributes: Whether to extract data from object attributes.            context: Additional context to pass to the validator.            by_alias: Whether to use the field's alias when validating against the provided input data.            by_name: Whether to use the field's name when validating against the provided input data.        Raises:            ValidationError: If the object could not be validated.        Returns:            The validated model instance.        """# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks__tracebackhide__=Trueifby_aliasisFalseandby_nameisnotTrue:raisePydanticUserError('At least one of `by_alias` or `by_name` must be set to True.',code='validate-by-alias-and-name-false',)returncls.__pydantic_validator__.validate_python(obj,strict=strict,from_attributes=from_attributes,context=context,by_alias=by_alias,by_name=by_name)@classmethoddefmodel_validate_json(cls,json_data:str|bytes|bytearray,*,strict:bool|None=None,context:Any|None=None,by_alias:bool|None=None,by_name:bool|None=None,)->Self:"""!!! abstract "Usage Documentation"            [JSON Parsing](../concepts/json.md#json-parsing)        Validate the given JSON data against the Pydantic model.        Args:            json_data: The JSON data to validate.            strict: Whether to enforce types strictly.            context: Extra variables to pass to the validator.            by_alias: Whether to use the field's alias when validating against the provided input data.            by_name: Whether to use the field's name when validating against the provided input data.        Returns:            The validated Pydantic model.        Raises:            ValidationError: If `json_data` is not a JSON string or the object could not be validated.        """# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks__tracebackhide__=Trueifby_aliasisFalseandby_nameisnotTrue:raisePydanticUserError('At least one of `by_alias` or `by_name` must be set to True.',code='validate-by-alias-and-name-false',)returncls.__pydantic_validator__.validate_json(json_data,strict=strict,context=context,by_alias=by_alias,by_name=by_name)@classmethoddefmodel_validate_strings(cls,obj:Any,*,strict:bool|None=None,context:Any|None=None,by_alias:bool|None=None,by_name:bool|None=None,)->Self:"""Validate the given object with string data against the Pydantic model.        Args:            obj: The object containing string data to validate.            strict: Whether to enforce types strictly.            context: Extra variables to pass to the validator.            by_alias: Whether to use the field's alias when validating against the provided input data.            by_name: Whether to use the field's name when validating against the provided input data.        Returns:            The validated Pydantic model.        """# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks__tracebackhide__=Trueifby_aliasisFalseandby_nameisnotTrue:raisePydanticUserError('At least one of `by_alias` or `by_name` must be set to True.',code='validate-by-alias-and-name-false',)returncls.__pydantic_validator__.validate_strings(obj,strict=strict,context=context,by_alias=by_alias,by_name=by_name)@classmethoddef__get_pydantic_core_schema__(cls,source:type[BaseModel],handler:GetCoreSchemaHandler,/)->CoreSchema:# This warning is only emitted when calling `super().__get_pydantic_core_schema__` from a model subclass.# In the generate schema logic, this method (`BaseModel.__get_pydantic_core_schema__`) is special cased to# *not* be called if not overridden.warnings.warn('The `__get_pydantic_core_schema__` method of the `BaseModel` class is deprecated. If you are calling ''`super().__get_pydantic_core_schema__` when overriding the method on a Pydantic model, consider using ''`handler(source)` instead. However, note that overriding this method on models can lead to unexpected ''side effects.',PydanticDeprecatedSince211,stacklevel=2,)# Logic copied over from `GenerateSchema._model_schema`:schema=cls.__dict__.get('__pydantic_core_schema__')ifschemaisnotNoneandnotisinstance(schema,_mock_val_ser.MockCoreSchema):returncls.__pydantic_core_schema__returnhandler(source)@classmethoddef__get_pydantic_json_schema__(cls,core_schema:CoreSchema,handler:GetJsonSchemaHandler,/,)->JsonSchemaValue:"""Hook into generating the model's JSON schema.        Args:            core_schema: A `pydantic-core` CoreSchema.                You can ignore this argument and call the handler with a new CoreSchema,                wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),                or just call the handler with the original schema.            handler: Call into Pydantic's internal JSON schema generation.                This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema                generation fails.                Since this gets called by `BaseModel.model_json_schema` you can override the                `schema_generator` argument to that function to change JSON schema generation globally                for a type.        Returns:            A JSON schema, as a Python object.        """returnhandler(core_schema)@classmethoddef__pydantic_init_subclass__(cls,**kwargs:Any)->None:"""This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`        only after the class is actually fully initialized. In particular, attributes like `model_fields` will        be present when this is called.        This is necessary because `__init_subclass__` will always be called by `type.__new__`,        and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that        `type.__new__` was called in such a manner that the class would already be sufficiently initialized.        This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,        any kwargs passed to the class definition that aren't used internally by pydantic.        Args:            **kwargs: Any keyword arguments passed to the class definition that aren't used internally                by pydantic.        """passdef__class_getitem__(cls,typevar_values:type[Any]|tuple[type[Any],...])->type[BaseModel]|_forward_ref.PydanticRecursiveRef:cached=_generics.get_cached_generic_type_early(cls,typevar_values)ifcachedisnotNone:returncachedifclsisBaseModel:raiseTypeError('Type parameters should be placed on typing.Generic, not BaseModel')ifnothasattr(cls,'__parameters__'):raiseTypeError(f'{cls} cannot be parametrized because it does not inherit from typing.Generic')ifnotcls.__pydantic_generic_metadata__['parameters']andtyping.Genericnotincls.__bases__:raiseTypeError(f'{cls} is not a generic class')ifnotisinstance(typevar_values,tuple):typevar_values=(typevar_values,)# For a model `class Model[T, U, V = int](BaseModel): ...` parametrized with `(str, bool)`,# this gives us `{T: str, U: bool, V: int}`:typevars_map=_generics.map_generic_model_arguments(cls,typevar_values)# We also update the provided args to use defaults values (`(str, bool)` becomes `(str, bool, int)`):typevar_values=tuple(vforvintypevars_map.values())if_utils.all_identical(typevars_map.keys(),typevars_map.values())andtypevars_map:submodel=cls# if arguments are equal to parameters it's the same object_generics.set_cached_generic_type(cls,typevar_values,submodel)else:parent_args=cls.__pydantic_generic_metadata__['args']ifnotparent_args:args=typevar_valueselse:args=tuple(_generics.replace_types(arg,typevars_map)forarginparent_args)origin=cls.__pydantic_generic_metadata__['origin']orclsmodel_name=origin.model_parametrized_name(args)params=tuple({param:Noneforparamin_generics.iter_contained_typevars(typevars_map.values())})# use dict as ordered setwith_generics.generic_recursion_self_type(origin,args)asmaybe_self_type:cached=_generics.get_cached_generic_type_late(cls,typevar_values,origin,args)ifcachedisnotNone:returncachedifmaybe_self_typeisnotNone:returnmaybe_self_type# Attempt to rebuild the origin in case new types have been definedtry:# depth 2 gets you above this __class_getitem__ call.# Note that we explicitly provide the parent ns, otherwise# `model_rebuild` will use the parent ns no matter if it is the ns of a module.# We don't want this here, as this has unexpected effects when a model# is being parametrized during a forward annotation evaluation.parent_ns=_typing_extra.parent_frame_namespace(parent_depth=2)or{}origin.model_rebuild(_types_namespace=parent_ns)exceptPydanticUndefinedAnnotation:# It's okay if it fails, it just means there are still undefined types# that could be evaluated later.passsubmodel=_generics.create_generic_submodel(model_name,origin,args,params)_generics.set_cached_generic_type(cls,typevar_values,submodel,origin,args)returnsubmodeldef__copy__(self)->Self:"""Returns a shallow copy of the model."""cls=type(self)m=cls.__new__(cls)_object_setattr(m,'__dict__',copy(self.__dict__))_object_setattr(m,'__pydantic_extra__',copy(self.__pydantic_extra__))_object_setattr(m,'__pydantic_fields_set__',copy(self.__pydantic_fields_set__))ifnothasattr(self,'__pydantic_private__')orself.__pydantic_private__isNone:_object_setattr(m,'__pydantic_private__',None)else:_object_setattr(m,'__pydantic_private__',{k:vfork,vinself.__pydantic_private__.items()ifvisnotPydanticUndefined},)returnmdef__deepcopy__(self,memo:dict[int,Any]|None=None)->Self:"""Returns a deep copy of the model."""cls=type(self)m=cls.__new__(cls)_object_setattr(m,'__dict__',deepcopy(self.__dict__,memo=memo))_object_setattr(m,'__pydantic_extra__',deepcopy(self.__pydantic_extra__,memo=memo))# This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],# and attempting a deepcopy would be marginally slower._object_setattr(m,'__pydantic_fields_set__',copy(self.__pydantic_fields_set__))ifnothasattr(self,'__pydantic_private__')orself.__pydantic_private__isNone:_object_setattr(m,'__pydantic_private__',None)else:_object_setattr(m,'__pydantic_private__',deepcopy({k:vfork,vinself.__pydantic_private__.items()ifvisnotPydanticUndefined},memo=memo),)returnmifnotTYPE_CHECKING:# We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access# The same goes for __setattr__ and __delattr__, see: https://github.com/pydantic/pydantic/issues/8643def__getattr__(self,item:str)->Any:private_attributes=object.__getattribute__(self,'__private_attributes__')ifiteminprivate_attributes:attribute=private_attributes[item]ifhasattr(attribute,'__get__'):returnattribute.__get__(self,type(self))# type: ignoretry:# Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has itemsreturnself.__pydantic_private__[item]# type: ignoreexceptKeyErrorasexc:raiseAttributeError(f'{type(self).__name__!r} object has no attribute{item!r}')fromexcelse:# `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.# See `BaseModel.__repr_args__` for more detailstry:pydantic_extra=object.__getattribute__(self,'__pydantic_extra__')exceptAttributeError:pydantic_extra=Noneifpydantic_extra:try:returnpydantic_extra[item]exceptKeyErrorasexc:raiseAttributeError(f'{type(self).__name__!r} object has no attribute{item!r}')fromexcelse:ifhasattr(self.__class__,item):returnsuper().__getattribute__(item)# Raises AttributeError if appropriateelse:# this is the current errorraiseAttributeError(f'{type(self).__name__!r} object has no attribute{item!r}')def__setattr__(self,name:str,value:Any)->None:if(setattr_handler:=self.__pydantic_setattr_handlers__.get(name))isnotNone:setattr_handler(self,name,value)# if None is returned from _setattr_handler, the attribute was set directlyelif(setattr_handler:=self._setattr_handler(name,value))isnotNone:setattr_handler(self,name,value)# call here to not memo on possibly unknown fieldsself.__pydantic_setattr_handlers__[name]=setattr_handler# memoize the handler for faster accessdef_setattr_handler(self,name:str,value:Any)->Callable[[BaseModel,str,Any],None]|None:"""Get a handler for setting an attribute on the model instance.            Returns:                A handler for setting an attribute on the model instance. Used for memoization of the handler.                Memoizing the handlers leads to a dramatic performance improvement in `__setattr__`                Returns `None` when memoization is not safe, then the attribute is set directly.            """cls=self.__class__ifnameincls.__class_vars__:raiseAttributeError(f'{name!r} is a ClassVar of `{cls.__name__}` and cannot be set on an instance. 'f'If you want to set a value on the class, use `{cls.__name__}.{name} = value`.')elifnot_fields.is_valid_field_name(name):if(attribute:=cls.__private_attributes__.get(name))isnotNone:ifhasattr(attribute,'__set__'):returnlambdamodel,_name,val:attribute.__set__(model,val)else:return_SIMPLE_SETATTR_HANDLERS['private']else:_object_setattr(self,name,value)returnNone# Can not return memoized handler with possibly freeform attr namesattr=getattr(cls,name,None)# NOTE: We currently special case properties and `cached_property`, but we might need# to generalize this to all data/non-data descriptors at some point. For non-data descriptors# (such as `cached_property`), it isn't obvious though. `cached_property` caches the value# to the instance's `__dict__`, but other non-data descriptors might do things differently.ifisinstance(attr,cached_property):return_SIMPLE_SETATTR_HANDLERS['cached_property']_check_frozen(cls,name,value)# We allow properties to be set only on non frozen models for now (to match dataclasses).# This can be changed if it ever gets requested.ifisinstance(attr,property):returnlambdamodel,_name,val:attr.__set__(model,val)elifcls.model_config.get('validate_assignment'):return_SIMPLE_SETATTR_HANDLERS['validate_assignment']elifnamenotincls.__pydantic_fields__:ifcls.model_config.get('extra')!='allow':# TODO - matching errorraiseValueError(f'"{cls.__name__}" object has no field "{name}"')elifattrisNone:# attribute does not exist, so put it in extraself.__pydantic_extra__[name]=valuereturnNone# Can not return memoized handler with possibly freeform attr nameselse:# attribute _does_ exist, and was not in extra, so update itreturn_SIMPLE_SETATTR_HANDLERS['extra_known']else:return_SIMPLE_SETATTR_HANDLERS['model_field']def__delattr__(self,item:str)->Any:cls=self.__class__ifiteminself.__private_attributes__:attribute=self.__private_attributes__[item]ifhasattr(attribute,'__delete__'):attribute.__delete__(self)# type: ignorereturntry:# Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has itemsdelself.__pydantic_private__[item]# type: ignorereturnexceptKeyErrorasexc:raiseAttributeError(f'{cls.__name__!r} object has no attribute{item!r}')fromexc# Allow cached properties to be deleted (even if the class is frozen):attr=getattr(cls,item,None)ifisinstance(attr,cached_property):returnobject.__delattr__(self,item)_check_frozen(cls,name=item,value=None)ifiteminself.__pydantic_fields__:object.__delattr__(self,item)elifself.__pydantic_extra__isnotNoneanditeminself.__pydantic_extra__:delself.__pydantic_extra__[item]else:try:object.__delattr__(self,item)exceptAttributeError:raiseAttributeError(f'{type(self).__name__!r} object has no attribute{item!r}')# Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by# type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:def__replace__(self,**changes:Any)->Self:returnself.model_copy(update=changes)def__getstate__(self)->dict[Any,Any]:private=self.__pydantic_private__ifprivate:private={k:vfork,vinprivate.items()ifvisnotPydanticUndefined}return{'__dict__':self.__dict__,'__pydantic_extra__':self.__pydantic_extra__,'__pydantic_fields_set__':self.__pydantic_fields_set__,'__pydantic_private__':private,}def__setstate__(self,state:dict[Any,Any])->None:_object_setattr(self,'__pydantic_fields_set__',state.get('__pydantic_fields_set__',{}))_object_setattr(self,'__pydantic_extra__',state.get('__pydantic_extra__',{}))_object_setattr(self,'__pydantic_private__',state.get('__pydantic_private__',{}))_object_setattr(self,'__dict__',state.get('__dict__',{}))ifnotTYPE_CHECKING:def__eq__(self,other:Any)->bool:ifisinstance(other,BaseModel):# When comparing instances of generic types for equality, as long as all field values are equal,# only require their generic origin types to be equal, rather than exact type equality.# This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1).self_type=self.__pydantic_generic_metadata__['origin']orself.__class__other_type=other.__pydantic_generic_metadata__['origin']orother.__class__# Perform common checks firstifnot(self_type==other_typeandgetattr(self,'__pydantic_private__',None)==getattr(other,'__pydantic_private__',None)andself.__pydantic_extra__==other.__pydantic_extra__):returnFalse# We only want to compare pydantic fields but ignoring fields is costly.# We'll perform a fast check first, and fallback only when needed# See GH-7444 and GH-7825 for rationale and a performance benchmark# First, do the fast (and sometimes faulty) __dict__ comparisonifself.__dict__==other.__dict__:# If the check above passes, then pydantic fields are equal, we can return earlyreturnTrue# We don't want to trigger unnecessary costly filtering of __dict__ on all unequal objects, so we return# early if there are no keys to ignore (we would just return False later on anyway)model_fields=type(self).__pydantic_fields__.keys()ifself.__dict__.keys()<=model_fieldsandother.__dict__.keys()<=model_fields:returnFalse# If we reach here, there are non-pydantic-fields keys, mapped to unequal values, that we need to ignore# Resort to costly filtering of the __dict__ objects# We use operator.itemgetter because it is much faster than dict comprehensions# NOTE: Contrary to standard python class and instances, when the Model class has a default value for an# attribute and the model instance doesn't have a corresponding attribute, accessing the missing attribute# raises an error in BaseModel.__getattr__ instead of returning the class attribute# So we can use operator.itemgetter() instead of operator.attrgetter()getter=operator.itemgetter(*model_fields)ifmodel_fieldselselambda_:_utils._SENTINELtry:returngetter(self.__dict__)==getter(other.__dict__)exceptKeyError:# In rare cases (such as when using the deprecated BaseModel.copy() method),# the __dict__ may not contain all model fields, which is how we can get here.# getter(self.__dict__) is much faster than any 'safe' method that accounts# for missing keys, and wrapping it in a `try` doesn't slow things down much# in the common case.self_fields_proxy=_utils.SafeGetItemProxy(self.__dict__)other_fields_proxy=_utils.SafeGetItemProxy(other.__dict__)returngetter(self_fields_proxy)==getter(other_fields_proxy)# other instance is not a BaseModelelse:returnNotImplemented# delegate to the other item in the comparisonifTYPE_CHECKING:# We put `__init_subclass__` in a TYPE_CHECKING block because, even though we want the type-checking benefits# described in the signature of `__init_subclass__` below, we don't want to modify the default behavior of# subclass initialization.def__init_subclass__(cls,**kwargs:Unpack[ConfigDict]):"""This signature is included purely to help type-checkers check arguments to class declaration, which            provides a way to conveniently set model_config key/value pairs.            ```python            from pydantic import BaseModel            class MyModel(BaseModel, extra='allow'): ...            ```            However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any            of the config arguments, and will only receive any keyword arguments passed during class initialization            that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)            Args:                **kwargs: Keyword arguments passed to the class definition, which set model_config            Note:                You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called                *after* the class is fully initialized.            """def__iter__(self)->TupleGenerator:"""So `dict(model)` works."""yield from[(k,v)for(k,v)inself.__dict__.items()ifnotk.startswith('_')]extra=self.__pydantic_extra__ifextra:yield fromextra.items()def__repr__(self)->str:returnf'{self.__repr_name__()}({self.__repr_str__(", ")})'def__repr_args__(self)->_repr.ReprArgs:# Eagerly create the repr of computed fields, as this may trigger access of cached properties and as such# modify the instance's `__dict__`. If we don't do it now, it could happen when iterating over the `__dict__`# below if the instance happens to be referenced in a field, and would modify the `__dict__` size *during* iteration.computed_fields_repr_args=[(k,getattr(self,k))fork,vinself.__pydantic_computed_fields__.items()ifv.repr]fork,vinself.__dict__.items():field=self.__pydantic_fields__.get(k)iffieldandfield.repr:ifvisnotself:yieldk,velse:yieldk,self.__repr_recursion__(v)# `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.# This can happen if a `ValidationError` is raised during initialization and the instance's# repr is generated as part of the exception handling. Therefore, we use `getattr` here# with a fallback, even though the type hints indicate the attribute will always be present.try:pydantic_extra=object.__getattribute__(self,'__pydantic_extra__')exceptAttributeError:pydantic_extra=Noneifpydantic_extraisnotNone:yield from((k,v)fork,vinpydantic_extra.items())yield fromcomputed_fields_repr_args# take logic from `_repr.Representation` without the side effects of inheritance, see #5740__repr_name__=_repr.Representation.__repr_name____repr_recursion__=_repr.Representation.__repr_recursion____repr_str__=_repr.Representation.__repr_str____pretty__=_repr.Representation.__pretty____rich_repr__=_repr.Representation.__rich_repr__def__str__(self)->str:returnself.__repr_str__(' ')# ##### Deprecated methods from v1 #####@property@typing_extensions.deprecated('The `__fields__` attribute is deprecated, use `model_fields` instead.',category=None)def__fields__(self)->dict[str,FieldInfo]:warnings.warn('The `__fields__` attribute is deprecated, use `model_fields` instead.',category=PydanticDeprecatedSince20,stacklevel=2,)returngetattr(type(self),'__pydantic_fields__',{})@property@typing_extensions.deprecated('The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.',category=None,)def__fields_set__(self)->set[str]:warnings.warn('The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.',category=PydanticDeprecatedSince20,stacklevel=2,)returnself.__pydantic_fields_set__@typing_extensions.deprecated('The `dict` method is deprecated; use `model_dump` instead.',category=None)defdict(# noqa: D102self,*,include:IncEx|None=None,exclude:IncEx|None=None,by_alias:bool=False,exclude_unset:bool=False,exclude_defaults:bool=False,exclude_none:bool=False,)->Dict[str,Any]:# noqa UP006warnings.warn('The `dict` method is deprecated; use `model_dump` instead.',category=PydanticDeprecatedSince20,stacklevel=2,)returnself.model_dump(include=include,exclude=exclude,by_alias=by_alias,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,)@typing_extensions.deprecated('The `json` method is deprecated; use `model_dump_json` instead.',category=None)defjson(# noqa: D102self,*,include:IncEx|None=None,exclude:IncEx|None=None,by_alias:bool=False,exclude_unset:bool=False,exclude_defaults:bool=False,exclude_none:bool=False,encoder:Callable[[Any],Any]|None=PydanticUndefined,# type: ignore[assignment]models_as_dict:bool=PydanticUndefined,# type: ignore[assignment]**dumps_kwargs:Any,)->str:warnings.warn('The `json` method is deprecated; use `model_dump_json` instead.',category=PydanticDeprecatedSince20,stacklevel=2,)ifencoderisnotPydanticUndefined:raiseTypeError('The `encoder` argument is no longer supported; use field serializers instead.')ifmodels_as_dictisnotPydanticUndefined:raiseTypeError('The `models_as_dict` argument is no longer supported; use a model serializer instead.')ifdumps_kwargs:raiseTypeError('`dumps_kwargs` keyword arguments are no longer supported.')returnself.model_dump_json(include=include,exclude=exclude,by_alias=by_alias,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,)@classmethod@typing_extensions.deprecated('The `parse_obj` method is deprecated; use `model_validate` instead.',category=None)defparse_obj(cls,obj:Any)->Self:# noqa: D102warnings.warn('The `parse_obj` method is deprecated; use `model_validate` instead.',category=PydanticDeprecatedSince20,stacklevel=2,)returncls.model_validate(obj)@classmethod@typing_extensions.deprecated('The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ''otherwise load the data then use `model_validate` instead.',category=None,)defparse_raw(# noqa: D102cls,b:str|bytes,*,content_type:str|None=None,encoding:str='utf8',proto:DeprecatedParseProtocol|None=None,allow_pickle:bool=False,)->Self:# pragma: no coverwarnings.warn('The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ''otherwise load the data then use `model_validate` instead.',category=PydanticDeprecatedSince20,stacklevel=2,)from.deprecatedimportparsetry:obj=parse.load_str_bytes(b,proto=proto,content_type=content_type,encoding=encoding,allow_pickle=allow_pickle,)except(ValueError,TypeError)asexc:importjson# try to match V1ifisinstance(exc,UnicodeDecodeError):type_str='value_error.unicodedecode'elifisinstance(exc,json.JSONDecodeError):type_str='value_error.jsondecode'elifisinstance(exc,ValueError):type_str='value_error'else:type_str='type_error'# ctx is missing here, but since we've added `input` to the error, we're not pretending it's the sameerror:pydantic_core.InitErrorDetails={# The type: ignore on the next line is to ignore the requirement of LiteralString'type':pydantic_core.PydanticCustomError(type_str,str(exc)),# type: ignore'loc':('__root__',),'input':b,}raisepydantic_core.ValidationError.from_exception_data(cls.__name__,[error])returncls.model_validate(obj)@classmethod@typing_extensions.deprecated('The `parse_file` method is deprecated; load the data from file, then if your data is JSON ''use `model_validate_json`, otherwise `model_validate` instead.',category=None,)defparse_file(# noqa: D102cls,path:str|Path,*,content_type:str|None=None,encoding:str='utf8',proto:DeprecatedParseProtocol|None=None,allow_pickle:bool=False,)->Self:warnings.warn('The `parse_file` method is deprecated; load the data from file, then if your data is JSON ''use `model_validate_json`, otherwise `model_validate` instead.',category=PydanticDeprecatedSince20,stacklevel=2,)from.deprecatedimportparseobj=parse.load_file(path,proto=proto,content_type=content_type,encoding=encoding,allow_pickle=allow_pickle,)returncls.parse_obj(obj)@classmethod@typing_extensions.deprecated('The `from_orm` method is deprecated; set '"`model_config['from_attributes']=True` and use `model_validate` instead.",category=None,)deffrom_orm(cls,obj:Any)->Self:# noqa: D102warnings.warn('The `from_orm` method is deprecated; set '"`model_config['from_attributes']=True` and use `model_validate` instead.",category=PydanticDeprecatedSince20,stacklevel=2,)ifnotcls.model_config.get('from_attributes',None):raisePydanticUserError('You must set the config attribute `from_attributes=True` to use from_orm',code=None)returncls.model_validate(obj)@classmethod@typing_extensions.deprecated('The `construct` method is deprecated; use `model_construct` instead.',category=None)defconstruct(cls,_fields_set:set[str]|None=None,**values:Any)->Self:# noqa: D102warnings.warn('The `construct` method is deprecated; use `model_construct` instead.',category=PydanticDeprecatedSince20,stacklevel=2,)returncls.model_construct(_fields_set=_fields_set,**values)@typing_extensions.deprecated('The `copy` method is deprecated; use `model_copy` instead. ''See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',category=None,)defcopy(self,*,include:AbstractSetIntStr|MappingIntStrAny|None=None,exclude:AbstractSetIntStr|MappingIntStrAny|None=None,update:Dict[str,Any]|None=None,# noqa UP006deep:bool=False,)->Self:# pragma: no cover"""Returns a copy of the model.        !!! warning "Deprecated"            This method is now deprecated; use `model_copy` instead.        If you need `include` or `exclude`, use:        ```python {test="skip" lint="skip"}        data = self.model_dump(include=include, exclude=exclude, round_trip=True)        data = {**data, **(update or {})}        copied = self.model_validate(data)        ```        Args:            include: Optional set or mapping specifying which fields to include in the copied model.            exclude: Optional set or mapping specifying which fields to exclude in the copied model.            update: Optional dictionary of field-value pairs to override field values in the copied model.            deep: If True, the values of fields that are Pydantic models will be deep-copied.        Returns:            A copy of the model with included, excluded and updated fields as specified.        """warnings.warn('The `copy` method is deprecated; use `model_copy` instead. ''See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',category=PydanticDeprecatedSince20,stacklevel=2,)from.deprecatedimportcopy_internalsvalues=dict(copy_internals._iter(self,to_dict=False,by_alias=False,include=include,exclude=exclude,exclude_unset=False),**(updateor{}),)ifself.__pydantic_private__isNone:private=Noneelse:private={k:vfork,vinself.__pydantic_private__.items()ifvisnotPydanticUndefined}ifself.__pydantic_extra__isNone:extra:dict[str,Any]|None=Noneelse:extra=self.__pydantic_extra__.copy()forkinlist(self.__pydantic_extra__):ifknotinvalues:# k was in the excludeextra.pop(k)forkinlist(values):ifkinself.__pydantic_extra__:# k must have come from extraextra[k]=values.pop(k)# new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwargifupdate:fields_set=self.__pydantic_fields_set__|update.keys()else:fields_set=set(self.__pydantic_fields_set__)# removing excluded fields from `__pydantic_fields_set__`ifexclude:fields_set-=set(exclude)returncopy_internals._copy_and_set_values(self,values,fields_set,extra,private,deep=deep)@classmethod@typing_extensions.deprecated('The `schema` method is deprecated; use `model_json_schema` instead.',category=None)defschema(# noqa: D102cls,by_alias:bool=True,ref_template:str=DEFAULT_REF_TEMPLATE)->Dict[str,Any]:# noqa UP006warnings.warn('The `schema` method is deprecated; use `model_json_schema` instead.',category=PydanticDeprecatedSince20,stacklevel=2,)returncls.model_json_schema(by_alias=by_alias,ref_template=ref_template)@classmethod@typing_extensions.deprecated('The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.',category=None,)defschema_json(# noqa: D102cls,*,by_alias:bool=True,ref_template:str=DEFAULT_REF_TEMPLATE,**dumps_kwargs:Any)->str:# pragma: no coverwarnings.warn('The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.',category=PydanticDeprecatedSince20,stacklevel=2,)importjsonfrom.deprecated.jsonimportpydantic_encoderreturnjson.dumps(cls.model_json_schema(by_alias=by_alias,ref_template=ref_template),default=pydantic_encoder,**dumps_kwargs,)@classmethod@typing_extensions.deprecated('The `validate` method is deprecated; use `model_validate` instead.',category=None)defvalidate(cls,value:Any)->Self:# noqa: D102warnings.warn('The `validate` method is deprecated; use `model_validate` instead.',category=PydanticDeprecatedSince20,stacklevel=2,)returncls.model_validate(value)@classmethod@typing_extensions.deprecated('The `update_forward_refs` method is deprecated; use `model_rebuild` instead.',category=None,)defupdate_forward_refs(cls,**localns:Any)->None:# noqa: D102warnings.warn('The `update_forward_refs` method is deprecated; use `model_rebuild` instead.',category=PydanticDeprecatedSince20,stacklevel=2,)iflocalns:# pragma: no coverraiseTypeError('`localns` arguments are not longer accepted.')cls.model_rebuild(force=True)@typing_extensions.deprecated('The private method `_iter` will be removed and should no longer be used.',category=None)def_iter(self,*args:Any,**kwargs:Any)->Any:warnings.warn('The private method `_iter` will be removed and should no longer be used.',category=PydanticDeprecatedSince20,stacklevel=2,)from.deprecatedimportcopy_internalsreturncopy_internals._iter(self,*args,**kwargs)@typing_extensions.deprecated('The private method `_copy_and_set_values` will be removed and should no longer be used.',category=None,)def_copy_and_set_values(self,*args:Any,**kwargs:Any)->Any:warnings.warn('The private method `_copy_and_set_values` will be removed and should no longer be used.',category=PydanticDeprecatedSince20,stacklevel=2,)from.deprecatedimportcopy_internalsreturncopy_internals._copy_and_set_values(self,*args,**kwargs)@classmethod@typing_extensions.deprecated('The private method `_get_value` will be removed and should no longer be used.',category=None,)def_get_value(cls,*args:Any,**kwargs:Any)->Any:warnings.warn('The private method `_get_value` will be removed and should no longer be used.',category=PydanticDeprecatedSince20,stacklevel=2,)from.deprecatedimportcopy_internalsreturncopy_internals._get_value(cls,*args,**kwargs)@typing_extensions.deprecated('The private method `_calculate_keys` will be removed and should no longer be used.',category=None,)def_calculate_keys(self,*args:Any,**kwargs:Any)->Any:warnings.warn('The private method `_calculate_keys` will be removed and should no longer be used.',category=PydanticDeprecatedSince20,stacklevel=2,)from.deprecatedimportcopy_internalsreturncopy_internals._calculate_keys(self,*args,**kwargs)

__init__

__init__(**data:Any)->None

RaisesValidationError if the input data cannot bevalidated to form a valid model.

self is explicitly positional-only to allowself as a field name.

Source code inpydantic/main.py
243244245246247248249250251252253254255256257258259260
def__init__(self,/,**data:Any)->None:"""Create a new model by parsing and validating input data from keyword arguments.    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be    validated to form a valid model.    `self` is explicitly positional-only to allow `self` as a field name.    """# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks__tracebackhide__=Truevalidated_self=self.__pydantic_validator__.validate_python(data,self_instance=self)ifselfisnotvalidated_self:warnings.warn('A custom validator is returning a value other than `self`.\n'"Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',stacklevel=2,)

model_configclass-attribute

model_config:ConfigDict=ConfigDict()

Configuration for the model, should be a dictionary conforming toConfigDict.

model_fieldsclassmethod

model_fields()->dict[str,FieldInfo]

A mapping of field names to their respectiveFieldInfo instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.Instead, you should access this attribute from the model class.

Source code inpydantic/main.py
265266267268269270271272273274
@_utils.deprecated_instance_property@classmethoddefmodel_fields(cls)->dict[str,FieldInfo]:"""A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.    !!! warning        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.        Instead, you should access this attribute from the model class.    """returngetattr(cls,'__pydantic_fields__',{})

model_computed_fieldsclassmethod

model_computed_fields()->dict[str,ComputedFieldInfo]

A mapping of computed field names to their respectiveComputedFieldInfo instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.Instead, you should access this attribute from the model class.

Source code inpydantic/main.py
276277278279280281282283284285
@_utils.deprecated_instance_property@classmethoddefmodel_computed_fields(cls)->dict[str,ComputedFieldInfo]:"""A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.    !!! warning        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.        Instead, you should access this attribute from the model class.    """returngetattr(cls,'__pydantic_computed_fields__',{})

__pydantic_core_schema__class-attribute

__pydantic_core_schema__:CoreSchema

The core schema of the model.

model_extraproperty

model_extra:dict[str,Any]|None

Get extra fields set during validation.

Returns:

TypeDescription
dict[str,Any] | None

A dictionary of extra fields, orNone ifconfig.extra is not set to"allow".

model_fields_setproperty

model_fields_set:set[str]

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

Returns:

TypeDescription
set[str]

A set of strings representing the fields that have been set,i.e. that were not filled from defaults.

model_constructclassmethod

model_construct(_fields_set:set[str]|None=None,**values:Any)->Self

Creates a new instance of theModel class with validated data.

Creates a new model setting__dict__ and__pydantic_fields_set__ from trusted or pre-validated data.Default values are respected, but no other validation is performed.

Note

model_construct() generally respects themodel_config.extra setting on the provided model.That is, ifmodel_config.extra == 'allow', then all extra passed values are added to the model instance's__dict__and__pydantic_extra__ fields. Ifmodel_config.extra == 'ignore' (the default), then all extra passed values are ignored.Because no validation is performed with a call tomodel_construct(), havingmodel_config.extra == 'forbid' does not result inan error if extra values are passed, but they will be ignored.

Parameters:

NameTypeDescriptionDefault
_fields_setset[str] | None

A set of field names that were originally explicitly set during instantiation. If provided,this is directly used for themodel_fields_set attribute.Otherwise, the field names from thevalues argument will be used.

None
valuesAny

Trusted or pre-validated data dictionary.

{}

Returns:

TypeDescription
Self

A new instance of theModel class with validated data.

Source code inpydantic/main.py
306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
@classmethoddefmodel_construct(cls,_fields_set:set[str]|None=None,**values:Any)->Self:# noqa: C901"""Creates a new instance of the `Model` class with validated data.    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.    Default values are respected, but no other validation is performed.    !!! note        `model_construct()` generally respects the `model_config.extra` setting on the provided model.        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in        an error if extra values are passed, but they will be ignored.    Args:        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.            Otherwise, the field names from the `values` argument will be used.        values: Trusted or pre-validated data dictionary.    Returns:        A new instance of the `Model` class with validated data.    """m=cls.__new__(cls)fields_values:dict[str,Any]={}fields_set=set()forname,fieldincls.__pydantic_fields__.items():iffield.aliasisnotNoneandfield.aliasinvalues:fields_values[name]=values.pop(field.alias)fields_set.add(name)if(namenotinfields_set)and(field.validation_aliasisnotNone):validation_aliases:list[str|AliasPath]=(field.validation_alias.choicesifisinstance(field.validation_alias,AliasChoices)else[field.validation_alias])foraliasinvalidation_aliases:ifisinstance(alias,str)andaliasinvalues:fields_values[name]=values.pop(alias)fields_set.add(name)breakelifisinstance(alias,AliasPath):value=alias.search_dict_for_path(values)ifvalueisnotPydanticUndefined:fields_values[name]=valuefields_set.add(name)breakifnamenotinfields_set:ifnameinvalues:fields_values[name]=values.pop(name)fields_set.add(name)elifnotfield.is_required():fields_values[name]=field.get_default(call_default_factory=True,validated_data=fields_values)if_fields_setisNone:_fields_set=fields_set_extra:dict[str,Any]|None=valuesifcls.model_config.get('extra')=='allow'elseNone_object_setattr(m,'__dict__',fields_values)_object_setattr(m,'__pydantic_fields_set__',_fields_set)ifnotcls.__pydantic_root_model__:_object_setattr(m,'__pydantic_extra__',_extra)ifcls.__pydantic_post_init__:m.model_post_init(None)# update private attributes with values setifhasattr(m,'__pydantic_private__')andm.__pydantic_private__isnotNone:fork,vinvalues.items():ifkinm.__private_attributes__:m.__pydantic_private__[k]=velifnotcls.__pydantic_root_model__:# Note: if there are any private attributes, cls.__pydantic_post_init__ would exist# Since it doesn't, that means that `__pydantic_private__` should be set to None_object_setattr(m,'__pydantic_private__',None)returnm

model_copy

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

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's__dict__ attribute is copied. Thismight have unexpected side effects if you store anything in it, on top of the modelfields (e.g. the value ofcached properties).

Parameters:

NameTypeDescriptionDefault
updateMapping[str,Any] | None

Values to change/add in the new model. Note: the data is not validatedbefore creating the new model. You should trust this data.

None
deepbool

Set toTrue to make a deep copy of the model.

False

Returns:

TypeDescription
Self

New model instance.

Source code inpydantic/main.py
387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
defmodel_copy(self,*,update:Mapping[str,Any]|None=None,deep:bool=False)->Self:"""!!! abstract "Usage Documentation"        [`model_copy`](../concepts/serialization.md#model_copy)    Returns a copy of the model.    !!! note        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This        might have unexpected side effects if you store anything in it, on top of the model        fields (e.g. the value of [cached properties][functools.cached_property]).    Args:        update: Values to change/add in the new model. Note: the data is not validated            before creating the new model. You should trust this data.        deep: Set to `True` to make a deep copy of the model.    Returns:        New model instance.    """copied=self.__deepcopy__()ifdeepelseself.__copy__()ifupdate:ifself.model_config.get('extra')=='allow':fork,vinupdate.items():ifkinself.__pydantic_fields__:copied.__dict__[k]=velse:ifcopied.__pydantic_extra__isNone:copied.__pydantic_extra__={}copied.__pydantic_extra__[k]=velse:copied.__dict__.update(update)copied.__pydantic_fields_set__.update(update.keys())returncopied

model_dump

model_dump(*,mode:Literal["json","python"]|str="python",include:IncEx|None=None,exclude:IncEx|None=None,context:Any|None=None,by_alias:bool|None=None,exclude_unset:bool=False,exclude_defaults:bool=False,exclude_none:bool=False,round_trip:bool=False,warnings:(bool|Literal["none","warn","error"])=True,fallback:Callable[[Any],Any]|None=None,serialize_as_any:bool=False)->dict[str,Any]

Usage Documentation

model_dump

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

Parameters:

NameTypeDescriptionDefault
modeLiteral['json', 'python'] |str

The mode in whichto_python should run.If mode is 'json', the output will only contain JSON serializable types.If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
includeIncEx | None

A set of fields to include in the output.

None
excludeIncEx | None

A set of fields to exclude from the output.

None
contextAny | None

Additional context to pass to the serializer.

None
by_aliasbool | None

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

None
exclude_unsetbool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaultsbool

Whether to exclude fields that are set to their default value.

False
exclude_nonebool

Whether to exclude fields that have a value ofNone.

False
round_tripbool

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

False
warningsbool |Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,"error" raises aPydanticSerializationError.

True
fallbackCallable[[Any],Any] | None

A function to call when an unknown value is encountered. If not provided,aPydanticSerializationError error is raised.

None
serialize_as_anybool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

TypeDescription
dict[str,Any]

A dictionary representation of the model.

Source code inpydantic/main.py
421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
defmodel_dump(self,*,mode:Literal['json','python']|str='python',include:IncEx|None=None,exclude:IncEx|None=None,context:Any|None=None,by_alias:bool|None=None,exclude_unset:bool=False,exclude_defaults:bool=False,exclude_none:bool=False,round_trip:bool=False,warnings:bool|Literal['none','warn','error']=True,fallback:Callable[[Any],Any]|None=None,serialize_as_any:bool=False,)->dict[str,Any]:"""!!! abstract "Usage Documentation"        [`model_dump`](../concepts/serialization.md#modelmodel_dump)    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.    Args:        mode: The mode in which `to_python` should run.            If mode is 'json', the output will only contain JSON serializable types.            If mode is 'python', the output may contain non-JSON-serializable Python objects.        include: A set of fields to include in the output.        exclude: A set of fields to exclude from the output.        context: Additional context to pass to the serializer.        by_alias: Whether to use the field's alias in the dictionary key if defined.        exclude_unset: Whether to exclude fields that have not been explicitly set.        exclude_defaults: Whether to exclude fields that are set to their default value.        exclude_none: Whether to exclude fields that have a value of `None`.        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].        fallback: A function to call when an unknown value is encountered. If not provided,            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.    Returns:        A dictionary representation of the model.    """returnself.__pydantic_serializer__.to_python(self,mode=mode,by_alias=by_alias,include=include,exclude=exclude,context=context,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,round_trip=round_trip,warnings=warnings,fallback=fallback,serialize_as_any=serialize_as_any,)

model_dump_json

model_dump_json(*,indent:int|None=None,include:IncEx|None=None,exclude:IncEx|None=None,context:Any|None=None,by_alias:bool|None=None,exclude_unset:bool=False,exclude_defaults:bool=False,exclude_none:bool=False,round_trip:bool=False,warnings:(bool|Literal["none","warn","error"])=True,fallback:Callable[[Any],Any]|None=None,serialize_as_any:bool=False)->str

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic'sto_json method.

Parameters:

NameTypeDescriptionDefault
indentint | None

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

None
includeIncEx | None

Field(s) to include in the JSON output.

None
excludeIncEx | None

Field(s) to exclude from the JSON output.

None
contextAny | None

Additional context to pass to the serializer.

None
by_aliasbool | None

Whether to serialize using field aliases.

None
exclude_unsetbool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaultsbool

Whether to exclude fields that are set to their default value.

False
exclude_nonebool

Whether to exclude fields that have a value ofNone.

False
round_tripbool

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

False
warningsbool |Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,"error" raises aPydanticSerializationError.

True
fallbackCallable[[Any],Any] | None

A function to call when an unknown value is encountered. If not provided,aPydanticSerializationError error is raised.

None
serialize_as_anybool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

TypeDescription
str

A JSON string representation of the model.

Source code inpydantic/main.py
479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
defmodel_dump_json(self,*,indent:int|None=None,include:IncEx|None=None,exclude:IncEx|None=None,context:Any|None=None,by_alias:bool|None=None,exclude_unset:bool=False,exclude_defaults:bool=False,exclude_none:bool=False,round_trip:bool=False,warnings:bool|Literal['none','warn','error']=True,fallback:Callable[[Any],Any]|None=None,serialize_as_any:bool=False,)->str:"""!!! abstract "Usage Documentation"        [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json)    Generates a JSON representation of the model using Pydantic's `to_json` method.    Args:        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.        include: Field(s) to include in the JSON output.        exclude: Field(s) to exclude from the JSON output.        context: Additional context to pass to the serializer.        by_alias: Whether to serialize using field aliases.        exclude_unset: Whether to exclude fields that have not been explicitly set.        exclude_defaults: Whether to exclude fields that are set to their default value.        exclude_none: Whether to exclude fields that have a value of `None`.        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].        fallback: A function to call when an unknown value is encountered. If not provided,            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.    Returns:        A JSON string representation of the model.    """returnself.__pydantic_serializer__.to_json(self,indent=indent,include=include,exclude=exclude,context=context,by_alias=by_alias,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,round_trip=round_trip,warnings=warnings,fallback=fallback,serialize_as_any=serialize_as_any,).decode()

model_json_schemaclassmethod

model_json_schema(by_alias:bool=True,ref_template:str=DEFAULT_REF_TEMPLATE,schema_generator:type[GenerateJsonSchema]=GenerateJsonSchema,mode:JsonSchemaMode="validation",)->dict[str,Any]

Generates a JSON schema for a model class.

Parameters:

NameTypeDescriptionDefault
by_aliasbool

Whether to use attribute aliases or not.

True
ref_templatestr

The reference template.

DEFAULT_REF_TEMPLATE
schema_generatortype[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass ofGenerateJsonSchema with your desired modifications

GenerateJsonSchema
modeJsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

TypeDescription
dict[str,Any]

The JSON schema for the given model class.

Source code inpydantic/main.py
535536537538539540541542543544545546547548549550551552553554555556557
@classmethoddefmodel_json_schema(cls,by_alias:bool=True,ref_template:str=DEFAULT_REF_TEMPLATE,schema_generator:type[GenerateJsonSchema]=GenerateJsonSchema,mode:JsonSchemaMode='validation',)->dict[str,Any]:"""Generates a JSON schema for a model class.    Args:        by_alias: Whether to use attribute aliases or not.        ref_template: The reference template.        schema_generator: To override the logic used to generate the JSON schema, as a subclass of            `GenerateJsonSchema` with your desired modifications        mode: The mode in which to generate the schema.    Returns:        The JSON schema for the given model class.    """returnmodel_json_schema(cls,by_alias=by_alias,ref_template=ref_template,schema_generator=schema_generator,mode=mode)

model_parametrized_nameclassmethod

model_parametrized_name(params:tuple[type[Any],...])->str

Compute the class name for parametrizations of generic classes.

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

Parameters:

NameTypeDescriptionDefault
paramstuple[type[Any], ...]

Tuple of types of the class. Given a generic classModel with 2 type variables and a concrete modelModel[str, int],the value(str, int) would be passed toparams.

required

Returns:

TypeDescription
str

String representing the new class whereparams are passed tocls as type variables.

Raises:

TypeDescription
TypeError

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

Source code inpydantic/main.py
559560561562563564565566567568569570571572573574575576577578579580581582583584
@classmethoddefmodel_parametrized_name(cls,params:tuple[type[Any],...])->str:"""Compute the class name for parametrizations of generic classes.    This method can be overridden to achieve a custom naming scheme for generic BaseModels.    Args:        params: Tuple of types of the class. Given a generic class            `Model` with 2 type variables and a concrete model `Model[str, int]`,            the value `(str, int)` would be passed to `params`.    Returns:        String representing the new class where `params` are passed to `cls` as type variables.    Raises:        TypeError: Raised when trying to generate concrete names for non-generic models.    """ifnotissubclass(cls,typing.Generic):raiseTypeError('Concrete names should only be generated for generic models.')# Any strings received should represent forward references, so we handle them specially below.# If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,# we may be able to remove this special case.param_names=[paramifisinstance(param,str)else_repr.display_as_type(param)forparaminparams]params_component=', '.join(param_names)returnf'{cls.__name__}[{params_component}]'

model_post_init

model_post_init(context:Any)->None

Override this method to perform additional initialization after__init__ andmodel_construct.This is useful if you want to do some validation that requires the entire model to be initialized.

Source code inpydantic/main.py
586587588589590
defmodel_post_init(self,context:Any,/)->None:"""Override this method to perform additional initialization after `__init__` and `model_construct`.    This is useful if you want to do some validation that requires the entire model to be initialized.    """pass

model_rebuildclassmethod

model_rebuild(*,force:bool=False,raise_errors:bool=True,_parent_namespace_depth:int=2,_types_namespace:MappingNamespace|None=None)->bool|None

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

This may be necessary when one of the annotations is a ForwardRef which could not be resolved duringthe initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

NameTypeDescriptionDefault
forcebool

Whether to force the rebuilding of the model schema, defaults toFalse.

False
raise_errorsbool

Whether to raise errors, defaults toTrue.

True
_parent_namespace_depthint

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

2
_types_namespaceMappingNamespace | None

The types namespace, defaults toNone.

None

Returns:

TypeDescription
bool | None

ReturnsNone if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuildingwas required, returnsTrue if rebuilding was successful, otherwiseFalse.

Source code inpydantic/main.py
592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
@classmethoddefmodel_rebuild(cls,*,force:bool=False,raise_errors:bool=True,_parent_namespace_depth:int=2,_types_namespace:MappingNamespace|None=None,)->bool|None:"""Try to rebuild the pydantic-core schema for the model.    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during    the initial attempt to build the schema, and automatic rebuilding fails.    Args:        force: Whether to force the rebuilding of the model schema, defaults to `False`.        raise_errors: Whether to raise errors, defaults to `True`.        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.        _types_namespace: The types namespace, defaults to `None`.    Returns:        Returns `None` if the schema is already "complete" and rebuilding was not required.        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.    """ifnotforceandcls.__pydantic_complete__:returnNoneforattrin('__pydantic_core_schema__','__pydantic_validator__','__pydantic_serializer__'):ifattrincls.__dict__andnotisinstance(getattr(cls,attr),_mock_val_ser.MockValSer):# Deleting the validator/serializer is necessary as otherwise they can get reused in# pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`# isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.# Same applies for the core schema that can be reused in schema generation.delattr(cls,attr)cls.__pydantic_complete__=Falseif_types_namespaceisnotNone:rebuild_ns=_types_namespaceelif_parent_namespace_depth>0:rebuild_ns=_typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth,force=True)or{}else:rebuild_ns={}parent_ns=_model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__)or{}ns_resolver=_namespace_utils.NsResolver(parent_namespace={**rebuild_ns,**parent_ns},)ifnotcls.__pydantic_fields_complete__:typevars_map=_generics.get_model_typevars_map(cls)try:cls.__pydantic_fields__=_fields.rebuild_model_fields(cls,ns_resolver=ns_resolver,typevars_map=typevars_map,)exceptNameErrorase:exc=PydanticUndefinedAnnotation.from_name_error(e)_mock_val_ser.set_model_mocks(cls,f'`{exc.name}`')ifraise_errors:raiseexcfromeifnotraise_errorsandnotcls.__pydantic_fields_complete__:# No need to continue with schema gen, it is guaranteed to failreturnFalseassertcls.__pydantic_fields_complete__return_model_construction.complete_model_class(cls,_config.ConfigWrapper(cls.model_config,check=False),raise_errors=raise_errors,ns_resolver=ns_resolver,)

model_validateclassmethod

model_validate(obj:Any,*,strict:bool|None=None,from_attributes:bool|None=None,context:Any|None=None,by_alias:bool|None=None,by_name:bool|None=None)->Self

Validate a pydantic model instance.

Parameters:

NameTypeDescriptionDefault
objAny

The object to validate.

required
strictbool | None

Whether to enforce types strictly.

None
from_attributesbool | None

Whether to extract data from object attributes.

None
contextAny | None

Additional context to pass to the validator.

None
by_aliasbool | None

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

None
by_namebool | None

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

None

Raises:

TypeDescription
ValidationError

If the object could not be validated.

Returns:

TypeDescription
Self

The validated model instance.

Source code inpydantic/main.py
669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
@classmethoddefmodel_validate(cls,obj:Any,*,strict:bool|None=None,from_attributes:bool|None=None,context:Any|None=None,by_alias:bool|None=None,by_name:bool|None=None,)->Self:"""Validate a pydantic model instance.    Args:        obj: The object to validate.        strict: Whether to enforce types strictly.        from_attributes: Whether to extract data from object attributes.        context: Additional context to pass to the validator.        by_alias: Whether to use the field's alias when validating against the provided input data.        by_name: Whether to use the field's name when validating against the provided input data.    Raises:        ValidationError: If the object could not be validated.    Returns:        The validated model instance.    """# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks__tracebackhide__=Trueifby_aliasisFalseandby_nameisnotTrue:raisePydanticUserError('At least one of `by_alias` or `by_name` must be set to True.',code='validate-by-alias-and-name-false',)returncls.__pydantic_validator__.validate_python(obj,strict=strict,from_attributes=from_attributes,context=context,by_alias=by_alias,by_name=by_name)

model_validate_jsonclassmethod

model_validate_json(json_data:str|bytes|bytearray,*,strict:bool|None=None,context:Any|None=None,by_alias:bool|None=None,by_name:bool|None=None)->Self

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

NameTypeDescriptionDefault
json_datastr |bytes |bytearray

The JSON data to validate.

required
strictbool | None

Whether to enforce types strictly.

None
contextAny | None

Extra variables to pass to the validator.

None
by_aliasbool | None

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

None
by_namebool | None

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

None

Returns:

TypeDescription
Self

The validated Pydantic model.

Raises:

TypeDescription
ValidationError

Ifjson_data is not a JSON string or the object could not be validated.

Source code inpydantic/main.py
709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
@classmethoddefmodel_validate_json(cls,json_data:str|bytes|bytearray,*,strict:bool|None=None,context:Any|None=None,by_alias:bool|None=None,by_name:bool|None=None,)->Self:"""!!! abstract "Usage Documentation"        [JSON Parsing](../concepts/json.md#json-parsing)    Validate the given JSON data against the Pydantic model.    Args:        json_data: The JSON data to validate.        strict: Whether to enforce types strictly.        context: Extra variables to pass to the validator.        by_alias: Whether to use the field's alias when validating against the provided input data.        by_name: Whether to use the field's name when validating against the provided input data.    Returns:        The validated Pydantic model.    Raises:        ValidationError: If `json_data` is not a JSON string or the object could not be validated.    """# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks__tracebackhide__=Trueifby_aliasisFalseandby_nameisnotTrue:raisePydanticUserError('At least one of `by_alias` or `by_name` must be set to True.',code='validate-by-alias-and-name-false',)returncls.__pydantic_validator__.validate_json(json_data,strict=strict,context=context,by_alias=by_alias,by_name=by_name)

model_validate_stringsclassmethod

model_validate_strings(obj:Any,*,strict:bool|None=None,context:Any|None=None,by_alias:bool|None=None,by_name:bool|None=None)->Self

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

Parameters:

NameTypeDescriptionDefault
objAny

The object containing string data to validate.

required
strictbool | None

Whether to enforce types strictly.

None
contextAny | None

Extra variables to pass to the validator.

None
by_aliasbool | None

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

None
by_namebool | None

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

None

Returns:

TypeDescription
Self

The validated Pydantic model.

Source code inpydantic/main.py
750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
@classmethoddefmodel_validate_strings(cls,obj:Any,*,strict:bool|None=None,context:Any|None=None,by_alias:bool|None=None,by_name:bool|None=None,)->Self:"""Validate the given object with string data against the Pydantic model.    Args:        obj: The object containing string data to validate.        strict: Whether to enforce types strictly.        context: Extra variables to pass to the validator.        by_alias: Whether to use the field's alias when validating against the provided input data.        by_name: Whether to use the field's name when validating against the provided input data.    Returns:        The validated Pydantic model.    """# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks__tracebackhide__=Trueifby_aliasisFalseandby_nameisnotTrue:raisePydanticUserError('At least one of `by_alias` or `by_name` must be set to True.',code='validate-by-alias-and-name-false',)returncls.__pydantic_validator__.validate_strings(obj,strict=strict,context=context,by_alias=by_alias,by_name=by_name)

pydantic.create_model

create_model(model_name:str,/,*,__config__:ConfigDict|None=None,__doc__:str|None=None,__base__:None=None,__module__:str=__name__,__validators__:(dict[str,Callable[...,Any]]|None)=None,__cls_kwargs__:dict[str,Any]|None=None,**field_definitions:Any|tuple[str,Any],)->type[BaseModel]
create_model(model_name:str,/,*,__config__:ConfigDict|None=None,__doc__:str|None=None,__base__:type[ModelT]|tuple[type[ModelT],...],__module__:str=__name__,__validators__:(dict[str,Callable[...,Any]]|None)=None,__cls_kwargs__:dict[str,Any]|None=None,**field_definitions:Any|tuple[str,Any],)->type[ModelT]
create_model(model_name:str,/,*,__config__:ConfigDict|None=None,__doc__:str|None=None,__base__:(type[ModelT]|tuple[type[ModelT],...]|None)=None,__module__:str|None=None,__validators__:(dict[str,Callable[...,Any]]|None)=None,__cls_kwargs__:dict[str,Any]|None=None,**field_definitions:Any|tuple[str,Any],)->type[ModelT]

Usage Documentation

Dynamic Model Creation

Dynamically creates and returns a new Pydantic model, in other words,create_model dynamically creates asubclass ofBaseModel.

Parameters:

NameTypeDescriptionDefault
model_namestr

The name of the newly created model.

required
__config__ConfigDict | None

The configuration of the new model.

None
__doc__str | None

The docstring of the new model.

None
__base__type[ModelT] |tuple[type[ModelT], ...] | None

The base class or classes for the new model.

None
__module__str | None

The name of the module that the model belongs to;ifNone, the value is taken fromsys._getframe(1)

None
__validators__dict[str,Callable[...,Any]] | None

A dictionary of methods that validate fields. The keys are the names of the validation methods tobe added to the model, and the values are the validation methods themselves. You can read more about functionalvalidatorshere.

None
__cls_kwargs__dict[str,Any] | None

A dictionary of keyword arguments for class creation, such asmetaclass.

None
**field_definitionsAny |tuple[str,Any]

Field definitions of the new model. Either:

  • a single element, representing the type annotation of the field.
  • a two-tuple, the first element being the type and the second element the assigned value (either a default or theField() function).
{}

Returns:

TypeDescription
type[ModelT]

The newmodel.

Raises:

TypeDescription
PydanticUserError

If__base__ and__config__ are both passed.

Source code inpydantic/main.py
16791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
defcreate_model(# noqa: C901model_name:str,/,*,__config__:ConfigDict|None=None,__doc__:str|None=None,__base__:type[ModelT]|tuple[type[ModelT],...]|None=None,__module__:str|None=None,__validators__:dict[str,Callable[...,Any]]|None=None,__cls_kwargs__:dict[str,Any]|None=None,# TODO PEP 747: replace `Any` by the TypeForm:**field_definitions:Any|tuple[str,Any],)->type[ModelT]:"""!!! abstract "Usage Documentation"        [Dynamic Model Creation](../concepts/models.md#dynamic-model-creation)    Dynamically creates and returns a new Pydantic model, in other words, `create_model` dynamically creates a    subclass of [`BaseModel`][pydantic.BaseModel].    Args:        model_name: The name of the newly created model.        __config__: The configuration of the new model.        __doc__: The docstring of the new model.        __base__: The base class or classes for the new model.        __module__: The name of the module that the model belongs to;            if `None`, the value is taken from `sys._getframe(1)`        __validators__: A dictionary of methods that validate fields. The keys are the names of the validation methods to            be added to the model, and the values are the validation methods themselves. You can read more about functional            validators [here](https://docs.pydantic.dev/2.9/concepts/validators/#field-validators).        __cls_kwargs__: A dictionary of keyword arguments for class creation, such as `metaclass`.        **field_definitions: Field definitions of the new model. Either:            - a single element, representing the type annotation of the field.            - a two-tuple, the first element being the type and the second element the assigned value              (either a default or the [`Field()`][pydantic.Field] function).    Returns:        The new [model][pydantic.BaseModel].    Raises:        PydanticUserError: If `__base__` and `__config__` are both passed.    """if__base__isNone:__base__=(cast('type[ModelT]',BaseModel),)elifnotisinstance(__base__,tuple):__base__=(__base__,)__cls_kwargs__=__cls_kwargs__or{}fields:dict[str,Any]={}annotations:dict[str,Any]={}forf_name,f_definfield_definitions.items():ifisinstance(f_def,tuple):iflen(f_def)!=2:raisePydanticUserError(f'Field definition for{f_name!r} should a single element representing the type or a two-tuple, the first element ''being the type and the second element the assigned value (either a default or the `Field()` function).',code='create-model-field-definitions',)annotations[f_name]=f_def[0]fields[f_name]=f_def[1]else:annotations[f_name]=f_defif__module__isNone:f=sys._getframe(1)__module__=f.f_globals['__name__']namespace:dict[str,Any]={'__annotations__':annotations,'__module__':__module__}if__doc__:namespace.update({'__doc__':__doc__})if__validators__:namespace.update(__validators__)namespace.update(fields)if__config__:namespace['model_config']=__config__resolved_bases=types.resolve_bases(__base__)meta,ns,kwds=types.prepare_class(model_name,resolved_bases,kwds=__cls_kwargs__)ifresolved_basesisnot__base__:ns['__orig_bases__']=__base__namespace.update(ns)returnmeta(model_name,resolved_bases,namespace,__pydantic_reset_parent_namespace__=False,_create_model_module=__module__,**kwds,)

[8]ページ先頭

©2009-2025 Movatter.jp