Movatterモバイル変換


[0]ホーム

URL:


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

Usage Errors

Pydantic attempts to provide useful errors. The following sections provide details on common errors developers mayencounter when working with Pydantic, along with suggestions for addressing the error condition.

Class not fully defined

This error is raised when a type referenced in an annotation of a pydantic-validated type(such as a subclass ofBaseModel, or a pydanticdataclass) is not defined:

fromtypingimportForwardReffrompydanticimportBaseModel,PydanticUserErrorUndefinedType=ForwardRef('UndefinedType')classFoobar(BaseModel):a:UndefinedTypetry:Foobar(a=1)exceptPydanticUserErrorasexc_info:assertexc_info.code=='class-not-fully-defined'

Or when the type has been defined after usage:

fromtypingimportOptionalfrompydanticimportBaseModel,PydanticUserErrorclassFoo(BaseModel):a:Optional['Bar']=Nonetry:# this doesn't work, see raised errorfoo=Foo(a={'b':{'a':None}})exceptPydanticUserErrorasexc_info:assertexc_info.code=='class-not-fully-defined'classBar(BaseModel):b:'Foo'# this works, thoughfoo=Foo(a={'b':{'a':None}})

For BaseModel subclasses, it can be fixed by defining the type and then calling.model_rebuild():

fromtypingimportOptionalfrompydanticimportBaseModelclassFoo(BaseModel):a:Optional['Bar']=NoneclassBar(BaseModel):b:'Foo'Foo.model_rebuild()foo=Foo(a={'b':{'a':None}})

In other cases, the error message should indicate how to rebuild the class with the appropriate type defined.

Custom JSON Schema

The__modify_schema__ method is no longer supported in V2. You should use the__get_pydantic_json_schema__ method instead.

The__modify_schema__ used to receive a single argument representing the JSON schema. See the example below:

Old way
frompydanticimportBaseModel,PydanticUserErrortry:classModel(BaseModel):@classmethoddef__modify_schema__(cls,field_schema):field_schema.update(examples=['example'])exceptPydanticUserErrorasexc_info:assertexc_info.code=='custom-json-schema'

The new method__get_pydantic_json_schema__ receives two arguments: the first is a dictionary denoted asCoreSchema,and the second a callablehandler that receives aCoreSchema as parameter, and returns a JSON schema. See the examplebelow:

New way
fromtypingimportAnyfrompydantic_coreimportCoreSchemafrompydanticimportBaseModel,GetJsonSchemaHandlerclassModel(BaseModel):@classmethoddef__get_pydantic_json_schema__(cls,core_schema:CoreSchema,handler:GetJsonSchemaHandler)->dict[str,Any]:json_schema=super().__get_pydantic_json_schema__(core_schema,handler)json_schema=handler.resolve_ref_schema(json_schema)json_schema.update(examples=['example'])returnjson_schemaprint(Model.model_json_schema())"""{'examples': ['example'], 'properties': {}, 'title': 'Model', 'type': 'object'}"""

Decorator on missing field

This error is raised when you define a decorator with a field that is not valid.

fromtypingimportAnyfrompydanticimportBaseModel,PydanticUserError,field_validatortry:classModel(BaseModel):a:str@field_validator('b')defcheck_b(cls,v:Any):returnvexceptPydanticUserErrorasexc_info:assertexc_info.code=='decorator-missing-field'

You can usecheck_fields=False if you're inheriting from the model and intended this.

fromtypingimportAnyfrompydanticimportBaseModel,create_model,field_validatorclassModel(BaseModel):@field_validator('a',check_fields=False)defcheck_a(cls,v:Any):returnvmodel=create_model('FooModel',a=(str,'cake'),__base__=Model)

Discriminator no field

This error is raised when a model in discriminated unions doesn't define a discriminator field.

fromtypingimportLiteral,UnionfrompydanticimportBaseModel,Field,PydanticUserErrorclassCat(BaseModel):c:strclassDog(BaseModel):pet_type:Literal['dog']d:strtry:classModel(BaseModel):pet:Union[Cat,Dog]=Field(discriminator='pet_type')number:intexceptPydanticUserErrorasexc_info:assertexc_info.code=='discriminator-no-field'
fromtypingimportLiteralfrompydanticimportBaseModel,Field,PydanticUserErrorclassCat(BaseModel):c:strclassDog(BaseModel):pet_type:Literal['dog']d:strtry:classModel(BaseModel):pet:Cat|Dog=Field(discriminator='pet_type')number:intexceptPydanticUserErrorasexc_info:assertexc_info.code=='discriminator-no-field'

Discriminator alias type

This error is raised when you define a non-string alias on a discriminator field.

fromtypingimportLiteral,UnionfrompydanticimportAliasChoices,BaseModel,Field,PydanticUserErrorclassCat(BaseModel):pet_type:Literal['cat']=Field(validation_alias=AliasChoices('Pet','PET'))c:strclassDog(BaseModel):pet_type:Literal['dog']d:strtry:classModel(BaseModel):pet:Union[Cat,Dog]=Field(discriminator='pet_type')number:intexceptPydanticUserErrorasexc_info:assertexc_info.code=='discriminator-alias-type'
fromtypingimportLiteralfrompydanticimportAliasChoices,BaseModel,Field,PydanticUserErrorclassCat(BaseModel):pet_type:Literal['cat']=Field(validation_alias=AliasChoices('Pet','PET'))c:strclassDog(BaseModel):pet_type:Literal['dog']d:strtry:classModel(BaseModel):pet:Cat|Dog=Field(discriminator='pet_type')number:intexceptPydanticUserErrorasexc_info:assertexc_info.code=='discriminator-alias-type'

Discriminator needs literal

This error is raised when you define a non-Literal type on a discriminator field.

fromtypingimportLiteral,UnionfrompydanticimportBaseModel,Field,PydanticUserErrorclassCat(BaseModel):pet_type:intc:strclassDog(BaseModel):pet_type:Literal['dog']d:strtry:classModel(BaseModel):pet:Union[Cat,Dog]=Field(discriminator='pet_type')number:intexceptPydanticUserErrorasexc_info:assertexc_info.code=='discriminator-needs-literal'
fromtypingimportLiteralfrompydanticimportBaseModel,Field,PydanticUserErrorclassCat(BaseModel):pet_type:intc:strclassDog(BaseModel):pet_type:Literal['dog']d:strtry:classModel(BaseModel):pet:Cat|Dog=Field(discriminator='pet_type')number:intexceptPydanticUserErrorasexc_info:assertexc_info.code=='discriminator-needs-literal'

Discriminator alias

This error is raised when you define different aliases on discriminator fields.

fromtypingimportLiteral,UnionfrompydanticimportBaseModel,Field,PydanticUserErrorclassCat(BaseModel):pet_type:Literal['cat']=Field(validation_alias='PET')c:strclassDog(BaseModel):pet_type:Literal['dog']=Field(validation_alias='Pet')d:strtry:classModel(BaseModel):pet:Union[Cat,Dog]=Field(discriminator='pet_type')number:intexceptPydanticUserErrorasexc_info:assertexc_info.code=='discriminator-alias'
fromtypingimportLiteralfrompydanticimportBaseModel,Field,PydanticUserErrorclassCat(BaseModel):pet_type:Literal['cat']=Field(validation_alias='PET')c:strclassDog(BaseModel):pet_type:Literal['dog']=Field(validation_alias='Pet')d:strtry:classModel(BaseModel):pet:Cat|Dog=Field(discriminator='pet_type')number:intexceptPydanticUserErrorasexc_info:assertexc_info.code=='discriminator-alias'

Invalid discriminator validator

This error is raised when you use a before, wrap, or plain validator on a discriminator field.

This is disallowed because the discriminator field is used to determine the type of the model to use for validation,so you can't use a validator that might change its value.

fromtypingimportLiteral,UnionfrompydanticimportBaseModel,Field,PydanticUserError,field_validatorclassCat(BaseModel):pet_type:Literal['cat']@field_validator('pet_type',mode='before')@classmethoddefvalidate_pet_type(cls,v):ifv=='kitten':return'cat'returnvclassDog(BaseModel):pet_type:Literal['dog']try:classModel(BaseModel):pet:Union[Cat,Dog]=Field(discriminator='pet_type')number:intexceptPydanticUserErrorasexc_info:assertexc_info.code=='discriminator-validator'
fromtypingimportLiteralfrompydanticimportBaseModel,Field,PydanticUserError,field_validatorclassCat(BaseModel):pet_type:Literal['cat']@field_validator('pet_type',mode='before')@classmethoddefvalidate_pet_type(cls,v):ifv=='kitten':return'cat'returnvclassDog(BaseModel):pet_type:Literal['dog']try:classModel(BaseModel):pet:Cat|Dog=Field(discriminator='pet_type')number:intexceptPydanticUserErrorasexc_info:assertexc_info.code=='discriminator-validator'

This can be worked around by using a standardUnion, dropping the discriminator:

fromtypingimportLiteral,UnionfrompydanticimportBaseModel,field_validatorclassCat(BaseModel):pet_type:Literal['cat']@field_validator('pet_type',mode='before')@classmethoddefvalidate_pet_type(cls,v):ifv=='kitten':return'cat'returnvclassDog(BaseModel):pet_type:Literal['dog']classModel(BaseModel):pet:Union[Cat,Dog]assertModel(pet={'pet_type':'kitten'}).pet.pet_type=='cat'
fromtypingimportLiteralfrompydanticimportBaseModel,field_validatorclassCat(BaseModel):pet_type:Literal['cat']@field_validator('pet_type',mode='before')@classmethoddefvalidate_pet_type(cls,v):ifv=='kitten':return'cat'returnvclassDog(BaseModel):pet_type:Literal['dog']classModel(BaseModel):pet:Cat|DogassertModel(pet={'pet_type':'kitten'}).pet.pet_type=='cat'

Callable discriminator case with no tag

This error is raised when aUnion that uses a callableDiscriminator doesn't haveTag annotations for all cases.

fromtypingimportAnnotated,UnionfrompydanticimportBaseModel,Discriminator,PydanticUserError,Tagdefmodel_x_discriminator(v):ifisinstance(v,str):return'str'ifisinstance(v,(dict,BaseModel)):return'model'# tag missing for both union choicestry:classDiscriminatedModel(BaseModel):x:Annotated[Union[str,'DiscriminatedModel'],Discriminator(model_x_discriminator),]exceptPydanticUserErrorasexc_info:assertexc_info.code=='callable-discriminator-no-tag'# tag missing for `'DiscriminatedModel'` union choicetry:classDiscriminatedModel(BaseModel):x:Annotated[Union[Annotated[str,Tag('str')],'DiscriminatedModel'],Discriminator(model_x_discriminator),]exceptPydanticUserErrorasexc_info:assertexc_info.code=='callable-discriminator-no-tag'# tag missing for `str` union choicetry:classDiscriminatedModel(BaseModel):x:Annotated[Union[str,Annotated['DiscriminatedModel',Tag('model')]],Discriminator(model_x_discriminator),]exceptPydanticUserErrorasexc_info:assertexc_info.code=='callable-discriminator-no-tag'
fromtypingimportAnnotated,UnionfrompydanticimportBaseModel,Discriminator,PydanticUserError,Tagdefmodel_x_discriminator(v):ifisinstance(v,str):return'str'ifisinstance(v,(dict,BaseModel)):return'model'# tag missing for both union choicestry:classDiscriminatedModel(BaseModel):x:Annotated[Union[str,'DiscriminatedModel'],Discriminator(model_x_discriminator),]exceptPydanticUserErrorasexc_info:assertexc_info.code=='callable-discriminator-no-tag'# tag missing for `'DiscriminatedModel'` union choicetry:classDiscriminatedModel(BaseModel):x:Annotated[Union[Annotated[str,Tag('str')],'DiscriminatedModel'],Discriminator(model_x_discriminator),]exceptPydanticUserErrorasexc_info:assertexc_info.code=='callable-discriminator-no-tag'# tag missing for `str` union choicetry:classDiscriminatedModel(BaseModel):x:Annotated[str|Annotated['DiscriminatedModel',Tag('model')],Discriminator(model_x_discriminator),]exceptPydanticUserErrorasexc_info:assertexc_info.code=='callable-discriminator-no-tag'

TypedDict version

This error is raised when you usetyping.TypedDictinstead oftyping_extensions.TypedDict on Python < 3.12.

Model parent field overridden

This error is raised when a field defined on a base class was overridden by a non-annotated attribute.

frompydanticimportBaseModel,PydanticUserErrorclassFoo(BaseModel):a:floattry:classBar(Foo):x:float=12.3a=123.0exceptPydanticUserErrorasexc_info:assertexc_info.code=='model-field-overridden'

Model field missing annotation

This error is raised when a field doesn't have an annotation.

frompydanticimportBaseModel,Field,PydanticUserErrortry:classModel(BaseModel):a=Field('foobar')b=NoneexceptPydanticUserErrorasexc_info:assertexc_info.code=='model-field-missing-annotation'

If the field is not meant to be a field, you may be able to resolve the errorby annotating it as aClassVar:

fromtypingimportClassVarfrompydanticimportBaseModelclassModel(BaseModel):a:ClassVar[str]

Or updatingmodel_config['ignored_types']:

frompydanticimportBaseModel,ConfigDictclassIgnoredType:passclassMyModel(BaseModel):model_config=ConfigDict(ignored_types=(IgnoredType,))_a=IgnoredType()_b:int=IgnoredType()_c:IgnoredType_d:IgnoredType=IgnoredType()

Config andmodel_config both defined

This error is raised whenclass Config andmodel_config are used together.

frompydanticimportBaseModel,ConfigDict,PydanticUserErrortry:classModel(BaseModel):model_config=ConfigDict(from_attributes=True)a:strclassConfig:from_attributes=TrueexceptPydanticUserErrorasexc_info:assertexc_info.code=='config-both'

Keyword arguments removed

This error is raised when the keyword arguments are not available in Pydantic V2.

For example,regex is removed from Pydantic V2:

frompydanticimportBaseModel,Field,PydanticUserErrortry:classModel(BaseModel):x:str=Field(regex='test')exceptPydanticUserErrorasexc_info:assertexc_info.code=='removed-kwargs'

Circular reference schema

This error is raised when a circular reference is found that would otherwise result in an infinite recursion.

For example, this is a valid type alias:

typeA=list[A]|None

while these are not:

typeA=AtypeB=CtypeC=B

JSON schema invalid type

This error is raised when Pydantic fails to generate a JSON schema for someCoreSchema.

frompydanticimportBaseModel,ImportString,PydanticUserErrorclassModel(BaseModel):a:ImportStringtry:Model.model_json_schema()exceptPydanticUserErrorasexc_info:assertexc_info.code=='invalid-for-json-schema'

JSON schema already used

This error is raised when the JSON schema generator has already been used to generate a JSON schema.You must create a new instance to generate a new JSON schema.

BaseModel instantiated

This error is raised when you instantiateBaseModel directly. Pydantic models should inherit fromBaseModel.

frompydanticimportBaseModel,PydanticUserErrortry:BaseModel()exceptPydanticUserErrorasexc_info:assertexc_info.code=='base-model-instantiated'

Undefined annotation

This error is raised when handling undefined annotations duringCoreSchema generation.

frompydanticimportBaseModel,PydanticUndefinedAnnotationclassModel(BaseModel):a:'B'# noqa F821try:Model.model_rebuild()exceptPydanticUndefinedAnnotationasexc_info:assertexc_info.code=='undefined-annotation'

Schema for unknown type

This error is raised when Pydantic fails to generate aCoreSchema for some type.

frompydanticimportBaseModel,PydanticUserErrortry:classModel(BaseModel):x:43=123exceptPydanticUserErrorasexc_info:assertexc_info.code=='schema-for-unknown-type'

Import error

This error is raised when you try to import an object that was available in Pydantic V1, but has been removed inPydantic V2.

See theMigration Guide for more information.

create_model field definitions

This error is raised when you provide invalid field definitions increate_model().

frompydanticimportPydanticUserError,create_modeltry:create_model('FooModel',foo=(str,'default value','more'))exceptPydanticUserErrorasexc_info:assertexc_info.code=='create-model-field-definitions'

The fields definition syntax can be found in thedynamic model creation documentation.

Validator with no fields

This error is raised when you use validator bare (with no fields).

frompydanticimportBaseModel,PydanticUserError,field_validatortry:classModel(BaseModel):a:str@field_validatordefchecker(cls,v):returnvexceptPydanticUserErrorasexc_info:assertexc_info.code=='validator-no-fields'

Validators should be used with fields and keyword arguments.

frompydanticimportBaseModel,field_validatorclassModel(BaseModel):a:str@field_validator('a')defchecker(cls,v):returnv

Invalid validator fields

This error is raised when you use a validator with non-string fields.

frompydanticimportBaseModel,PydanticUserError,field_validatortry:classModel(BaseModel):a:strb:str@field_validator(['a','b'])defcheck_fields(cls,v):returnvexceptPydanticUserErrorasexc_info:assertexc_info.code=='validator-invalid-fields'

Fields should be passed as separate string arguments:

frompydanticimportBaseModel,field_validatorclassModel(BaseModel):a:strb:str@field_validator('a','b')defcheck_fields(cls,v):returnv

Validator on instance method

This error is raised when you apply a validator on an instance method.

frompydanticimportBaseModel,PydanticUserError,field_validatortry:classModel(BaseModel):a:int=1@field_validator('a')defcheck_a(self,value):returnvalueexceptPydanticUserErrorasexc_info:assertexc_info.code=='validator-instance-method'

json_schema_input_type used with the wrong mode

This error is raised when you explicitly specify a value for thejson_schema_input_typeargument andmode isn't set to either'before','plain' or'wrap'.

frompydanticimportBaseModel,PydanticUserError,field_validatortry:classModel(BaseModel):a:int=1@field_validator('a',mode='after',json_schema_input_type=int)@classmethoddefcheck_a(self,value):returnvalueexceptPydanticUserErrorasexc_info:assertexc_info.code=='validator-input-type'

Documenting the JSON Schema input type is only possible for validators where the givenvalue can be anything. That is why it isn't available forafter validators, wherethe value is first validated against the type annotation.

Root validator,pre,skip_on_failure

If you use@root_validator withpre=False (the default) you MUST specifyskip_on_failure=True.Theskip_on_failure=False option is no longer available.

If you were not trying to setskip_on_failure=False, you can safely setskip_on_failure=True.If you do, this root validator will no longer be called if validation fails for any of the fields.

Please see theMigration Guide for more details.

model_serializer instance methods

@model_serializer must be applied to instance methods.

This error is raised when you applymodel_serializer on an instance method withoutself:

frompydanticimportBaseModel,PydanticUserError,model_serializertry:classMyModel(BaseModel):a:int@model_serializerdef_serialize(slf,x,y,z):returnslfexceptPydanticUserErrorasexc_info:assertexc_info.code=='model-serializer-instance-method'

Or on a class method:

frompydanticimportBaseModel,PydanticUserError,model_serializertry:classMyModel(BaseModel):a:int@model_serializer@classmethoddef_serialize(self,x,y,z):returnselfexceptPydanticUserErrorasexc_info:assertexc_info.code=='model-serializer-instance-method'

validator,field,config, andinfo

Thefield andconfig parameters are not available in Pydantic V2.Please use theinfo parameter instead.

You can access the configuration viainfo.config,but it is a dictionary instead of an object like it was in Pydantic V1.

Thefield argument is no longer available.

Pydantic V1 validator signature

This error is raised when you use an unsupported signature for Pydantic V1-style validator.

importwarningsfrompydanticimportBaseModel,PydanticUserError,validatorwarnings.filterwarnings('ignore',category=DeprecationWarning)try:classModel(BaseModel):a:int@validator('a')defcheck_a(cls,value,foo):returnvalueexceptPydanticUserErrorasexc_info:assertexc_info.code=='validator-v1-signature'

Unrecognizedfield_validator signature

This error is raised when afield_validator ormodel_validator function has the wrong signature.

frompydanticimportBaseModel,PydanticUserError,field_validatortry:classModel(BaseModel):a:str@field_validator('a')@classmethoddefcheck_a(cls):return'a'exceptPydanticUserErrorasexc_info:assertexc_info.code=='validator-signature'

Unrecognizedfield_serializer signature

This error is raised when thefield_serializer function has the wrong signature.

frompydanticimportBaseModel,PydanticUserError,field_serializertry:classModel(BaseModel):x:int@field_serializer('x')defno_args():return'x'exceptPydanticUserErrorasexc_info:assertexc_info.code=='field-serializer-signature'

Valid field serializer signatures are:

frompydanticimportFieldSerializationInfo,SerializerFunctionWrapHandler,field_serializer# an instance method with the default mode or `mode='plain'`@field_serializer('x')# or @field_serializer('x', mode='plain')defser_x(self,value:Any,info:FieldSerializationInfo):...# a static method or function with the default mode or `mode='plain'`@field_serializer('x')# or @field_serializer('x', mode='plain')@staticmethoddefser_x(value:Any,info:FieldSerializationInfo):...# equivalent todefser_x(value:Any,info:FieldSerializationInfo):...serializer('x')(ser_x)# an instance method with `mode='wrap'`@field_serializer('x',mode='wrap')defser_x(self,value:Any,nxt:SerializerFunctionWrapHandler,info:FieldSerializationInfo):...# a static method or function with `mode='wrap'`@field_serializer('x',mode='wrap')@staticmethoddefser_x(value:Any,nxt:SerializerFunctionWrapHandler,info:FieldSerializationInfo):...# equivalent todefser_x(value:Any,nxt:SerializerFunctionWrapHandler,info:FieldSerializationInfo):...serializer('x')(ser_x)# For all of these, you can also choose to omit the `info` argument, for example:@field_serializer('x')defser_x(self,value:Any):...@field_serializer('x',mode='wrap')defser_x(self,value:Any,handler:SerializerFunctionWrapHandler):...

Unrecognizedmodel_serializer signature

This error is raised when themodel_serializer function has the wrong signature.

frompydanticimportBaseModel,PydanticUserError,model_serializertry:classMyModel(BaseModel):a:int@model_serializerdef_serialize(self,x,y,z):returnselfexceptPydanticUserErrorasexc_info:assertexc_info.code=='model-serializer-signature'

Valid model serializer signatures are:

frompydanticimportSerializerFunctionWrapHandler,SerializationInfo,model_serializer# an instance method with the default mode or `mode='plain'`@model_serializer# or model_serializer(mode='plain')defmod_ser(self,info:SerializationInfo):...# an instance method with `mode='wrap'`@model_serializer(mode='wrap')defmod_ser(self,handler:SerializerFunctionWrapHandler,info:SerializationInfo):# For all of these, you can also choose to omit the `info` argument, for example:@model_serializer(mode='plain')defmod_ser(self):...@model_serializer(mode='wrap')defmod_ser(self,handler:SerializerFunctionWrapHandler):...

Multiple field serializers

This error is raised when multiplemodel_serializer functions are defined for a field.

frompydanticimportBaseModel,PydanticUserError,field_serializertry:classMyModel(BaseModel):x:inty:int@field_serializer('x','y')defserializer1(v):returnf'{v:,}'@field_serializer('x')defserializer2(v):returnvexceptPydanticUserErrorasexc_info:assertexc_info.code=='multiple-field-serializers'

Invalid annotated type

This error is raised when an annotation cannot annotate a type.

fromtypingimportAnnotatedfrompydanticimportBaseModel,FutureDate,PydanticUserErrortry:classModel(BaseModel):foo:Annotated[str,FutureDate()]exceptPydanticUserErrorasexc_info:assertexc_info.code=='invalid-annotated-type'

config is unused withTypeAdapter

You will get this error if you try to passconfig toTypeAdapter when the type is a type thathas its own config that cannot be overridden (currently this is onlyBaseModel,TypedDict anddataclass):

fromtyping_extensionsimportTypedDictfrompydanticimportConfigDict,PydanticUserError,TypeAdapterclassMyTypedDict(TypedDict):x:inttry:TypeAdapter(MyTypedDict,config=ConfigDict(strict=True))exceptPydanticUserErrorasexc_info:assertexc_info.code=='type-adapter-config-unused'
fromtypingimportTypedDictfrompydanticimportConfigDict,PydanticUserError,TypeAdapterclassMyTypedDict(TypedDict):x:inttry:TypeAdapter(MyTypedDict,config=ConfigDict(strict=True))exceptPydanticUserErrorasexc_info:assertexc_info.code=='type-adapter-config-unused'

Instead you'll need to subclass the type and override or set the config on it:

fromtyping_extensionsimportTypedDictfrompydanticimportConfigDict,TypeAdapterclassMyTypedDict(TypedDict):x:int# or `model_config = ...` for BaseModel__pydantic_config__=ConfigDict(strict=True)TypeAdapter(MyTypedDict)# ok
fromtypingimportTypedDictfrompydanticimportConfigDict,TypeAdapterclassMyTypedDict(TypedDict):x:int# or `model_config = ...` for BaseModel__pydantic_config__=ConfigDict(strict=True)TypeAdapter(MyTypedDict)# ok

Cannot specifymodel_config['extra'] withRootModel

BecauseRootModel is not capable of storing or even accepting extra fields during initialization, we raise an errorif you try to specify a value for the config setting'extra' when creating a subclass ofRootModel:

frompydanticimportPydanticUserError,RootModeltry:classMyRootModel(RootModel):model_config={'extra':'allow'}root:intexceptPydanticUserErrorasexc_info:assertexc_info.code=='root-model-extra'

Cannot evaluate type annotation

Because type annotations are evaluatedafter assignments, you might get unexpected results when using a type annotation namethat clashes with one of your fields. We raise an error in the following case:

fromdatetimeimportdatefrompydanticimportBaseModel,FieldclassModel(BaseModel):date:date=Field(description='A date')

As a workaround, you can either use an alias or change your import:

importdatetime# Or `from datetime import date as _date`frompydanticimportBaseModel,FieldclassModel(BaseModel):date:datetime.date=Field(description='A date')

Incompatibledataclassinit andextra settings

Pydantic does not allow the specification of theextra='allow' setting on a dataclasswhile any of the fields haveinit=False set.

Thus, you may not do something like the following:

frompydanticimportConfigDict,Fieldfrompydantic.dataclassesimportdataclass@dataclass(config=ConfigDict(extra='allow'))classA:a:int=Field(init=False,default=1)

The above snippet results in the following error during schema building for theA dataclass:

pydantic.errors.PydanticUserError: Field a has `init=False` and dataclass has config setting `extra="allow"`.This combination is not allowed.

Incompatibleinit andinit_var settings ondataclass field

Theinit=False andinit_var=True settings are mutually exclusive. Doing so results in thePydanticUserError shown in the example below.

frompydanticimportFieldfrompydantic.dataclassesimportdataclass@dataclassclassFoo:bar:str=Field(init=False,init_var=True)"""pydantic.errors.PydanticUserError: Dataclass field bar has init=False and init_var=True, but these are mutually exclusive."""

model_config is used as a model field

This error is raised whenmodel_config is used as the name of a field.

frompydanticimportBaseModel,PydanticUserErrortry:classModel(BaseModel):model_config:strexceptPydanticUserErrorasexc_info:assertexc_info.code=='model-config-invalid-field-name'

with_config is used on aBaseModel subclass

This error is raised when thewith_config decorator is used on a class which is already a Pydantic model (use themodel_config attribute instead).

frompydanticimportBaseModel,PydanticUserError,with_configtry:@with_config({'allow_inf_nan':True})classModel(BaseModel):bar:strexceptPydanticUserErrorasexc_info:assertexc_info.code=='with-config-on-model'

dataclass is used on aBaseModel subclass

This error is raised when the Pydanticdataclass decorator is used on a class which is alreadya Pydantic model.

frompydanticimportBaseModel,PydanticUserErrorfrompydantic.dataclassesimportdataclasstry:@dataclassclassModel(BaseModel):bar:strexceptPydanticUserErrorasexc_info:assertexc_info.code=='dataclass-on-model'

Unsupported type forvalidate_call

validate_call has some limitations on the callables it can validate. This error is raised when you try to use it with an unsupported callable.Currently the supported callables are functions (including lambdas, but not built-ins) and methods and instances ofpartial.In the case ofpartial, the function being partially applied must be one of the supported callables.

@classmethod,@staticmethod, and@property

These decorators must be put beforevalidate_call.

frompydanticimportPydanticUserError,validate_call# errortry:classA:@validate_call@classmethoddeff1(cls):...exceptPydanticUserErrorasexc_info:assertexc_info.code=='validate-call-type'# correct@classmethod@validate_calldeff2(cls):...

Classes

While classes are callables themselves,validate_call can't be applied on them, as it needs to know about which method to use (__init__ or__new__) to fetch type annotations. If you want to validate the constructor of a class, you should putvalidate_call on top of the appropriate method instead.

frompydanticimportPydanticUserError,validate_call# errortry:@validate_callclassA1:...exceptPydanticUserErrorasexc_info:assertexc_info.code=='validate-call-type'# correctclassA2:@validate_calldef__init__(self):...@validate_calldef__new__(cls):...

Callable instances

Although instances can be callable by implementing a__call__ method, currently the instances of these types cannot be validated withvalidate_call.This may change in the future, but for now, you should usevalidate_call explicitly on__call__ instead.

frompydanticimportPydanticUserError,validate_call# errortry:classA1:def__call__(self):...validate_call(A1())exceptPydanticUserErrorasexc_info:assertexc_info.code=='validate-call-type'# correctclassA2:@validate_calldef__call__(self):...

Invalid signature

This is generally less common, but a possible reason is that you are trying to validate a method that doesn't have at least one argument (usuallyself).

frompydanticimportPydanticUserError,validate_calltry:classA:deff():...validate_call(A().f)exceptPydanticUserErrorasexc_info:assertexc_info.code=='validate-call-type'

Unpack used without aTypedDict

This error is raised whenUnpack is used with something other thanaTypedDict class object to type hint variadic keyword parameters.

For reference, see therelated specification section andPEP 692.

fromtyping_extensionsimportUnpackfrompydanticimportPydanticUserError,validate_calltry:@validate_calldeffunc(**kwargs:Unpack[int]):passexceptPydanticUserErrorasexc_info:assertexc_info.code=='unpack-typed-dict'
fromtypingimportUnpackfrompydanticimportPydanticUserError,validate_calltry:@validate_calldeffunc(**kwargs:Unpack[int]):passexceptPydanticUserErrorasexc_info:assertexc_info.code=='unpack-typed-dict'

Overlapping unpackedTypedDict fields and arguments

This error is raised when the typed dictionary used to type hint variadic keywords parameters has field namesoverlapping with other parameters (unlesspositional only).

For reference, see therelated specification section andPEP 692.

fromtyping_extensionsimportTypedDict,UnpackfrompydanticimportPydanticUserError,validate_callclassTD(TypedDict):a:inttry:@validate_calldeffunc(a:int,**kwargs:Unpack[TD]):passexceptPydanticUserErrorasexc_info:assertexc_info.code=='overlapping-unpack-typed-dict'
fromtyping_extensionsimportTypedDictfromtypingimportUnpackfrompydanticimportPydanticUserError,validate_callclassTD(TypedDict):a:inttry:@validate_calldeffunc(a:int,**kwargs:Unpack[TD]):passexceptPydanticUserErrorasexc_info:assertexc_info.code=='overlapping-unpack-typed-dict'
fromtypingimportTypedDict,UnpackfrompydanticimportPydanticUserError,validate_callclassTD(TypedDict):a:inttry:@validate_calldeffunc(a:int,**kwargs:Unpack[TD]):passexceptPydanticUserErrorasexc_info:assertexc_info.code=='overlapping-unpack-typed-dict'

InvalidSelf type

Currently,Self can only be used to annotate a field of a class (specifically, subclasses ofBaseModel,NamedTuple,TypedDict, or dataclasses). Attempting to useSelf in any other ways will raise this error.

fromtyping_extensionsimportSelffrompydanticimportPydanticUserError,validate_calltry:@validate_calldeffunc(self:Self):passexceptPydanticUserErrorasexc_info:assertexc_info.code=='invalid-self-type'
fromtypingimportSelffrompydanticimportPydanticUserError,validate_calltry:@validate_calldeffunc(self:Self):passexceptPydanticUserErrorasexc_info:assertexc_info.code=='invalid-self-type'

The following example ofvalidate_call() will also raise this error, even though it is correct from a type-checking perspective. This may be supported in the future.

fromtyping_extensionsimportSelffrompydanticimportBaseModel,PydanticUserError,validate_calltry:classA(BaseModel):@validate_calldeffunc(self,arg:Self):passexceptPydanticUserErrorasexc_info:assertexc_info.code=='invalid-self-type'
fromtypingimportSelffrompydanticimportBaseModel,PydanticUserError,validate_calltry:classA(BaseModel):@validate_calldeffunc(self,arg:Self):passexceptPydanticUserErrorasexc_info:assertexc_info.code=='invalid-self-type'

validate_by_alias andvalidate_by_name both set toFalse

This error is raised when you setvalidate_by_alias andvalidate_by_name toFalse in the configuration.

This is not allowed because it would make it impossible to populate attributes.

frompydanticimportBaseModel,ConfigDict,Field,PydanticUserErrortry:classModel(BaseModel):a:int=Field(alias='A')model_config=ConfigDict(validate_by_alias=False,validate_by_name=False)exceptPydanticUserErrorasexc_info:assertexc_info.code=='validate-by-alias-and-name-false'

[8]ページ先頭

©2009-2025 Movatter.jp