Movatterモバイル変換


[0]ホーム

URL:


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

Validation Errors

Pydantic attempts to provide useful validation errors. Below are details on common validation errors usersmay encounter when working with pydantic, together with some suggestions on how to fix them.

arguments_type

This error is raised when an object that would be passed as arguments to a function during validation is notatuple,list, ordict. BecauseNamedTuple uses function calls in its implementation, that is one way toproduce this error:

fromtypingimportNamedTuplefrompydanticimportBaseModel,ValidationErrorclassMyNamedTuple(NamedTuple):x:intclassMyModel(BaseModel):field:MyNamedTupletry:MyModel.model_validate({'field':'invalid'})exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'arguments_type'

assertion_error

This error is raised when a failingassert statement is encountered during validation:

frompydanticimportBaseModel,ValidationError,field_validatorclassModel(BaseModel):x:int@field_validator('x')@classmethoddefforce_x_positive(cls,v):assertv>0returnvtry:Model(x=-1)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'assertion_error'

bool_parsing

This error is raised when the input value is a string that is not valid for coercion to a boolean:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:boolModel(x='true')# OKtry:Model(x='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'bool_parsing'

bool_type

This error is raised when the input value's type is not valid for abool field:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:booltry:Model(x=None)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'bool_type'

This error is also raised for strict fields when the input value is not an instance ofbool.

bytes_invalid_encoding

This error is raised when abytes value is invalid under the configured encoding.In the following example,'a' is invalid hex (odd number of digits).

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:bytesmodel_config={'val_json_bytes':'hex'}try:Model(x='a')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'bytes_invalid_encoding'

bytes_too_long

This error is raised when the length of abytes value is greater than the field'smax_length constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:bytes=Field(max_length=3)try:Model(x=b'test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'bytes_too_long'

bytes_too_short

This error is raised when the length of abytes value is less than the field'smin_length constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:bytes=Field(min_length=3)try:Model(x=b't')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'bytes_too_short'

bytes_type

This error is raised when the input value's type is not valid for abytes field:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:bytestry:Model(x=123)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'bytes_type'

This error is also raised for strict fields when the input value is not an instance ofbytes.

callable_type

This error is raised when the input value is not valid as aCallable:

fromtypingimportAny,CallablefrompydanticimportBaseModel,ImportString,ValidationErrorclassModel(BaseModel):x:ImportString[Callable[[Any],Any]]Model(x='math:cos')# OKtry:Model(x='os.path')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'callable_type'
fromtypingimportAnyfromcollections.abcimportCallablefrompydanticimportBaseModel,ImportString,ValidationErrorclassModel(BaseModel):x:ImportString[Callable[[Any],Any]]Model(x='math:cos')# OKtry:Model(x='os.path')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'callable_type'

complex_str_parsing

This error is raised when the input value is a string but cannot be parsed as a complex number becauseit does not follow therule in Python:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):num:complextry:# Complex numbers in json are expected to be valid complex strings.# This value `abc` is not a valid complex string.Model.model_validate_json('{"num": "abc"}')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'complex_str_parsing'

complex_type

This error is raised when the input value cannot be interpreted as a complex number:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):num:complextry:Model(num=False)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'complex_type'

dataclass_exact_type

This error is raised when validating a dataclass withstrict=True and the input is not an instance of the dataclass:

importpydantic.dataclassesfrompydanticimportTypeAdapter,ValidationError@pydantic.dataclasses.dataclassclassMyDataclass:x:stradapter=TypeAdapter(MyDataclass)print(adapter.validate_python(MyDataclass(x='test'),strict=True))#> MyDataclass(x='test')print(adapter.validate_python({'x':'test'}))#> MyDataclass(x='test')try:adapter.validate_python({'x':'test'},strict=True)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'dataclass_exact_type'

dataclass_type

This error is raised when the input value is not valid for adataclass field:

frompydanticimportValidationError,dataclasses@dataclasses.dataclassclassInner:x:int@dataclasses.dataclassclassOuter:y:InnerOuter(y=Inner(x=1))# OKtry:Outer(y=1)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'dataclass_type'

date_from_datetime_inexact

This error is raised when the inputdatetime value provided for adate field has a nonzero time component.For a timestamp to parse into a field of typedate, the time components must all be zero:

fromdatetimeimportdate,datetimefrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:dateModel(x='2023-01-01')# OKModel(x=datetime(2023,1,1))# OKtry:Model(x=datetime(2023,1,1,12))exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'date_from_datetime_inexact'

date_from_datetime_parsing

This error is raised when the input value is a string that cannot be parsed for adate field:

fromdatetimeimportdatefrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:datetry:Model(x='XX1494012000')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'date_from_datetime_parsing'

date_future

This error is raised when the input value provided for aFutureDate field is not in the future:

fromdatetimeimportdatefrompydanticimportBaseModel,FutureDate,ValidationErrorclassModel(BaseModel):x:FutureDatetry:Model(x=date(2000,1,1))exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'date_future'

date_parsing

This error is raised when validating JSON where the input value is string that cannot be parsed for adate field:

importjsonfromdatetimeimportdatefrompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:date=Field(strict=True)try:Model.model_validate_json(json.dumps({'x':'1'}))exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'date_parsing'

date_past

This error is raised when the value provided for aPastDate field is not in the past:

fromdatetimeimportdate,timedeltafrompydanticimportBaseModel,PastDate,ValidationErrorclassModel(BaseModel):x:PastDatetry:Model(x=date.today()+timedelta(1))exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'date_past'

date_type

This error is raised when the input value's type is not valid for adate field:

fromdatetimeimportdatefrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:datetry:Model(x=None)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'date_type'

This error is also raised for strict fields when the input value is not an instance ofdate.

datetime_from_date_parsing

This error is raised when the input value is a string that cannot be parsed for adatetime field:

fromdatetimeimportdatetimefrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:datetimetry:# there is no 13th monthModel(x='2023-13-01')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'datetime_from_date_parsing'

datetime_future

This error is raised when the value provided for aFutureDatetime field is not in the future:

fromdatetimeimportdatetimefrompydanticimportBaseModel,FutureDatetime,ValidationErrorclassModel(BaseModel):x:FutureDatetimetry:Model(x=datetime(2000,1,1))exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'datetime_future'

datetime_object_invalid

This error is raised when something about thedatetime object is not valid:

fromdatetimeimportdatetime,tzinfofrompydanticimportAwareDatetime,BaseModel,ValidationErrorclassCustomTz(tzinfo):# utcoffset is not implemented!deftzname(self,_dt):return'CustomTZ'classModel(BaseModel):x:AwareDatetimetry:Model(x=datetime(2023,1,1,tzinfo=CustomTz()))exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'datetime_object_invalid'

datetime_parsing

This error is raised when the value is a string that cannot be parsed for adatetime field:

importjsonfromdatetimeimportdatetimefrompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:datetime=Field(strict=True)try:Model.model_validate_json(json.dumps({'x':'not a datetime'}))exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'datetime_parsing'

datetime_past

This error is raised when the value provided for aPastDatetime field is not in the past:

fromdatetimeimportdatetime,timedeltafrompydanticimportBaseModel,PastDatetime,ValidationErrorclassModel(BaseModel):x:PastDatetimetry:Model(x=datetime.now()+timedelta(100))exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'datetime_past'

datetime_type

This error is raised when the input value's type is not valid for adatetime field:

fromdatetimeimportdatetimefrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:datetimetry:Model(x=None)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'datetime_type'

This error is also raised for strict fields when the input value is not an instance ofdatetime.

decimal_max_digits

This error is raised when the value provided for aDecimal has too many digits:

fromdecimalimportDecimalfrompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:Decimal=Field(max_digits=3)try:Model(x='42.1234')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'decimal_max_digits'

decimal_max_places

This error is raised when the value provided for aDecimal has too many digits after the decimal point:

fromdecimalimportDecimalfrompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:Decimal=Field(decimal_places=3)try:Model(x='42.1234')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'decimal_max_places'

decimal_parsing

This error is raised when the value provided for aDecimal could not be parsed as a decimal number:

fromdecimalimportDecimalfrompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:Decimal=Field(decimal_places=3)try:Model(x='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'decimal_parsing'

decimal_type

This error is raised when the value provided for aDecimal is of the wrong type:

fromdecimalimportDecimalfrompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:Decimal=Field(decimal_places=3)try:Model(x=[1,2,3])exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'decimal_type'

This error is also raised for strict fields when the input value is not an instance ofDecimal.

decimal_whole_digits

This error is raised when the value provided for aDecimal has more digits before the decimal point thanmax_digits -decimal_places (as long as both are specified):

fromdecimalimportDecimalfrompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:Decimal=Field(max_digits=6,decimal_places=3)try:Model(x='12345.6')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'decimal_whole_digits'

default_factory_not_called

This error is raised when adefault factory taking validated datacan't be called, because validation failed on previous fields:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):a:int=Field(gt=10)b:int=Field(default_factory=lambdadata:data['a'])try:Model(a=1)exceptValidationErrorasexc:print(exc)"""    2 validation errors for Model    a      Input should be greater than 10 [type=greater_than, input_value=1, input_type=int]    b      The default factory uses validated data, but at least one validation error occurred [type=default_factory_not_called]    """print(repr(exc.errors()[1]['type']))#> 'default_factory_not_called'

dict_type

This error is raised when the input value's type is notdict for adict field:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:dicttry:Model(x=['1','2'])exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'dict_type'

enum

This error is raised when the input value does not exist in anenum field members:

fromenumimportEnumfrompydanticimportBaseModel,ValidationErrorclassMyEnum(str,Enum):option='option'classModel(BaseModel):x:MyEnumtry:Model(x='other_option')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'enum'

extra_forbidden

This error is raised when the input value contains extra fields, butmodel_config['extra'] == 'forbid':

frompydanticimportBaseModel,ConfigDict,ValidationErrorclassModel(BaseModel):x:strmodel_config=ConfigDict(extra='forbid')try:Model(x='test',y='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'extra_forbidden'

You can read more about theextra configuration in theExtra Attributes section.

finite_number

This error is raised when the value is infinite, or too large to be represented as a 64-bit floating point numberduring validation:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:inttry:Model(x=2.2250738585072011e308)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'finite_number'

float_parsing

This error is raised when the value is a string that can't be parsed as afloat:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:floattry:Model(x='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'float_parsing'

float_type

This error is raised when the input value's type is not valid for afloat field:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:floattry:Model(x=None)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'float_type'

frozen_field

This error is raised when you attempt to assign a value to a field withfrozen=True, or to delete such a field:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:str=Field('test',frozen=True)model=Model()try:model.x='test1'exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'frozen_field'try:delmodel.xexceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'frozen_field'

frozen_instance

This error is raised whenfrozen is set in theconfiguration and you attempt to delete or assign a new value toany of the fields:

frompydanticimportBaseModel,ConfigDict,ValidationErrorclassModel(BaseModel):x:intmodel_config=ConfigDict(frozen=True)m=Model(x=1)try:m.x=2exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'frozen_instance'try:delm.xexceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'frozen_instance'

frozen_set_type

This error is raised when the input value's type is not valid for afrozenset field:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:frozensettry:model=Model(x='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'frozen_set_type'

get_attribute_error

This error is raised whenmodel_config['from_attributes'] == True and an error is raised while reading the attributes:

frompydanticimportBaseModel,ConfigDict,ValidationErrorclassFoobar:def__init__(self):self.x=1@propertydefy(self):raiseRuntimeError('intentional error')classModel(BaseModel):x:inty:strmodel_config=ConfigDict(from_attributes=True)try:Model.model_validate(Foobar())exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'get_attribute_error'

greater_than

This error is raised when the value is not greater than the field'sgt constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:int=Field(gt=10)try:Model(x=10)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'greater_than'

greater_than_equal

This error is raised when the value is not greater than or equal to the field'sge constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:int=Field(ge=10)try:Model(x=9)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'greater_than_equal'

int_from_float

This error is raised when you provide afloat value for anint field:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:inttry:Model(x=0.5)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'int_from_float'

int_parsing

This error is raised when the value can't be parsed asint:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:inttry:Model(x='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'int_parsing'

int_parsing_size

This error is raised when attempting to parse a python or JSON value from a string outside the maximum range that Pythonstr toint parsing permits:

importjsonfrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:int# from PythonassertModel(x='1'*4_300).x==int('1'*4_300)# OKtoo_long='1'*4_301try:Model(x=too_long)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'int_parsing_size'# from JSONtry:Model.model_validate_json(json.dumps({'x':too_long}))exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'int_parsing_size'

int_type

This error is raised when the input value's type is not valid for anint field:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:inttry:Model(x=None)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'int_type'

invalid_key

This error is raised when attempting to validate adict that has a key that is not an instance ofstr:

frompydanticimportBaseModel,ConfigDict,ValidationErrorclassModel(BaseModel):x:intmodel_config=ConfigDict(extra='allow')try:Model.model_validate({'x':1,b'y':2})exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'invalid_key'

is_instance_of

This error is raised when the input value is not an instance of the expected type:

frompydanticimportBaseModel,ConfigDict,ValidationErrorclassNested:x:strclassModel(BaseModel):y:Nestedmodel_config=ConfigDict(arbitrary_types_allowed=True)try:Model(y='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'is_instance_of'

is_subclass_of

This error is raised when the input value is not a subclass of the expected type:

frompydanticimportBaseModel,ValidationErrorclassNested:x:strclassModel(BaseModel):y:type[Nested]try:Model(y='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'is_subclass_of'

iterable_type

This error is raised when the input value is not valid as anIterable:

fromcollections.abcimportIterablefrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):y:Iterable[str]try:Model(y=123)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'iterable_type'

iteration_error

This error is raised when an error occurs during iteration:

frompydanticimportBaseModel,ValidationErrordefgen():yield1raiseRuntimeError('error')classModel(BaseModel):x:list[int]try:Model(x=gen())exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'iteration_error'

json_invalid

This error is raised when the input value is not a valid JSON string:

frompydanticimportBaseModel,Json,ValidationErrorclassModel(BaseModel):x:Jsontry:Model(x='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'json_invalid'

json_type

This error is raised when the input value is of a type that cannot be parsed as JSON:

frompydanticimportBaseModel,Json,ValidationErrorclassModel(BaseModel):x:Jsontry:Model(x=None)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'json_type'

less_than

This error is raised when the input value is not less than the field'slt constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:int=Field(lt=10)try:Model(x=10)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'less_than'

less_than_equal

This error is raised when the input value is not less than or equal to the field'sle constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:int=Field(le=10)try:Model(x=11)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'less_than_equal'

list_type

This error is raised when the input value's type is not valid for alist field:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:list[int]try:Model(x=1)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'list_type'

literal_error

This error is raised when the input value is not one of the expected literal values:

fromtypingimportLiteralfrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:Literal['a','b']Model(x='a')# OKtry:Model(x='c')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'literal_error'

mapping_type

This error is raised when a problem occurs during validation due to a failure in a call to the methods from theMapping protocol, such as.items():

fromcollections.abcimportMappingfrompydanticimportBaseModel,ValidationErrorclassBadMapping(Mapping):defitems(self):raiseValueError()def__iter__(self):raiseValueError()def__getitem__(self,key):raiseValueError()def__len__(self):return1classModel(BaseModel):x:dict[str,str]try:Model(x=BadMapping())exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'mapping_type'

missing

This error is raised when there are required fields missing from the input value:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:strtry:Model()exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'missing'

missing_argument

This error is raised when a required positional-or-keyword argument is not passed to a function decorated withvalidate_call:

frompydanticimportValidationError,validate_call@validate_calldeffoo(a:int):returnatry:foo()exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'missing_argument'

missing_keyword_only_argument

This error is raised when a required keyword-only argument is not passed to a function decorated withvalidate_call:

frompydanticimportValidationError,validate_call@validate_calldeffoo(*,a:int):returnatry:foo()exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'missing_keyword_only_argument'

missing_positional_only_argument

This error is raised when a required positional-only argument is not passed to a function decorated withvalidate_call:

frompydanticimportValidationError,validate_call@validate_calldeffoo(a:int,/):returnatry:foo()exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'missing_positional_only_argument'

missing_sentinel_error

This error is raised when the experimentalMISSING sentinel is the only value allowed, and wasn'tprovided during validation:

frompydanticimportBaseModel,ValidationErrorfrompydantic.experimental.missing_sentinelimportMISSINGclassModel(BaseModel):f:MISSINGtry:Model(f=1)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'missing_sentinel_error'

model_attributes_type

This error is raised when the input value is not a valid dictionary, model instance, or instance that fields can be extracted from:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):a:intb:int# simply validating a dictprint(Model.model_validate({'a':1,'b':2}))#> a=1 b=2classCustomObj:def__init__(self,a,b):self.a=aself.b=b# using from attributes to extract fields from an objectsprint(Model.model_validate(CustomObj(3,4),from_attributes=True))#> a=3 b=4try:Model.model_validate('not an object',from_attributes=True)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'model_attributes_type'

model_type

This error is raised when the input to a model is not an instance of the model or dict:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):a:intb:int# simply validating a dictm=Model.model_validate({'a':1,'b':2})print(m)#> a=1 b=2# validating an existing model instanceprint(Model.model_validate(m))#> a=1 b=2try:Model.model_validate('not an object')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'model_type'

multiple_argument_values

This error is raised when you provide multiple values for a single argument while calling a function decorated withvalidate_call:

frompydanticimportValidationError,validate_call@validate_calldeffoo(a:int):returnatry:foo(1,a=2)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'multiple_argument_values'

multiple_of

This error is raised when the input is not a multiple of a field'smultiple_of constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:int=Field(multiple_of=5)try:Model(x=1)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'multiple_of'

needs_python_object

This type of error is raised when validation is attempted from a format that cannot be converted to a Python object.For example, we cannot checkisinstance orissubclass from JSON:

importjsonfrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):bm:type[BaseModel]try:Model.model_validate_json(json.dumps({'bm':'not a basemodel class'}))exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'needs_python_object'

no_such_attribute

This error is raised whenvalidate_assignment=True in the config, and you attempt to assign a value to an attributethat is not an existing field:

frompydanticimportConfigDict,ValidationError,dataclasses@dataclasses.dataclass(config=ConfigDict(validate_assignment=True))classMyDataclass:x:intm=MyDataclass(x=1)try:m.y=10exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'no_such_attribute'

none_required

This error is raised when the input value is notNone for a field that requiresNone:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:Nonetry:Model(x=1)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'none_required'

Note

You may encounter this error when there is a naming collision in your model between a field name and its type. More specifically, this error is likely to be thrown when the default value of that field isNone.

For example, the following would yield thenone_required validation error since the fieldint is set to a default value ofNone and has the exact same name as its type, which causes problems with validation.

fromtypingimportOptionalfrompydanticimportBaseModelclassM1(BaseModel):int:Optional[int]=Nonem=M1(int=123)# errors

recursion_loop

This error is raised when a cyclic reference is detected:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:list['Model']d={'x':[]}d['x'].append(d)try:Model(**d)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'recursion_loop'

set_item_not_hashable

This error is raised when an unhashable value is validated against aset or afrozenset:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:set[object]classUnhashable:__hash__=Nonetry:Model(x=[{'a':'b'},Unhashable()])exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'set_item_not_hashable'print(repr(exc.errors()[1]['type']))#> 'set_item_not_hashable'

set_type

This error is raised when the value type is not valid for aset field:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:set[int]try:Model(x='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'set_type'

string_pattern_mismatch

This error is raised when the input value doesn't match the field'spattern constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:str=Field(pattern='test')try:Model(x='1')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'string_pattern_mismatch'

string_sub_type

This error is raised when the value is an instance of a strict subtype ofstr when the field is strict:

fromenumimportEnumfrompydanticimportBaseModel,Field,ValidationErrorclassMyEnum(str,Enum):foo='foo'classModel(BaseModel):x:str=Field(strict=True)try:Model(x=MyEnum.foo)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'string_sub_type'

string_too_long

This error is raised when the input value is a string whose length is greater than the field'smax_length constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:str=Field(max_length=3)try:Model(x='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'string_too_long'

string_too_short

This error is raised when the input value is a string whose length is less than the field'smin_length constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:str=Field(min_length=3)try:Model(x='t')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'string_too_short'

string_type

This error is raised when the input value's type is not valid for astr field:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:strtry:Model(x=1)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'string_type'

This error is also raised for strict fields when the input value is not an instance ofstr.

string_unicode

This error is raised when the value cannot be parsed as a Unicode string:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:strtry:Model(x=b'\x81')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'string_unicode'

time_delta_parsing

This error is raised when the input value is a string that cannot be parsed for atimedelta field:

fromdatetimeimporttimedeltafrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:timedeltatry:Model(x='t')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'time_delta_parsing'

time_delta_type

This error is raised when the input value's type is not valid for atimedelta field:

fromdatetimeimporttimedeltafrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:timedeltatry:Model(x=None)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'time_delta_type'

This error is also raised for strict fields when the input value is not an instance oftimedelta.

time_parsing

This error is raised when the input value is a string that cannot be parsed for atime field:

fromdatetimeimporttimefrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:timetry:Model(x='25:20:30.400')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'time_parsing'

time_type

This error is raised when the value type is not valid for atime field:

fromdatetimeimporttimefrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:timetry:Model(x=None)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'time_type'

This error is also raised for strict fields when the input value is not an instance oftime.

timezone_aware

This error is raised when thedatetime value provided for a timezone-awaredatetime fielddoesn't have timezone information:

fromdatetimeimportdatetimefrompydanticimportAwareDatetime,BaseModel,ValidationErrorclassModel(BaseModel):x:AwareDatetimetry:Model(x=datetime.now())exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'timezone_aware'

timezone_naive

This error is raised when thedatetime value provided for a timezone-naivedatetime fieldhas timezone info:

fromdatetimeimportdatetime,timezonefrompydanticimportBaseModel,NaiveDatetime,ValidationErrorclassModel(BaseModel):x:NaiveDatetimetry:Model(x=datetime.now(tz=timezone.utc))exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'timezone_naive'

too_long

This error is raised when the input value's length is greater than the field'smax_length constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:list[int]=Field(max_length=3)try:Model(x=[1,2,3,4])exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'too_long'

too_short

This error is raised when the value length is less than the field'smin_length constraint:

frompydanticimportBaseModel,Field,ValidationErrorclassModel(BaseModel):x:list[int]=Field(min_length=3)try:Model(x=[1,2])exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'too_short'

tuple_type

This error is raised when the input value's type is not valid for atuple field:

frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):x:tuple[int]try:Model(x=None)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'tuple_type'

This error is also raised for strict fields when the input value is not an instance oftuple.

unexpected_keyword_argument

This error is raised when you provide a value by keyword for a positional-onlyargument while calling a function decorated withvalidate_call:

frompydanticimportValidationError,validate_call@validate_calldeffoo(a:int,/):returnatry:foo(a=2)exceptValidationErrorasexc:print(repr(exc.errors()[1]['type']))#> 'unexpected_keyword_argument'

It is also raised when using pydantic.dataclasses andextra=forbid:

frompydanticimportTypeAdapter,ValidationErrorfrompydantic.dataclassesimportdataclass@dataclass(config={'extra':'forbid'})classFoo:bar:inttry:TypeAdapter(Foo).validate_python({'bar':1,'foobar':2})exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'unexpected_keyword_argument'

unexpected_positional_argument

This error is raised when you provide a positional value for a keyword-onlyargument while calling a function decorated withvalidate_call:

frompydanticimportValidationError,validate_call@validate_calldeffoo(*,a:int):returnatry:foo(2)exceptValidationErrorasexc:print(repr(exc.errors()[1]['type']))#> 'unexpected_positional_argument'

union_tag_invalid

This error is raised when the input's discriminator is not one of the expected values:

fromtypingimportLiteral,UnionfrompydanticimportBaseModel,Field,ValidationErrorclassBlackCat(BaseModel):pet_type:Literal['blackcat']classWhiteCat(BaseModel):pet_type:Literal['whitecat']classModel(BaseModel):cat:Union[BlackCat,WhiteCat]=Field(discriminator='pet_type')try:Model(cat={'pet_type':'dog'})exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'union_tag_invalid'
fromtypingimportLiteralfrompydanticimportBaseModel,Field,ValidationErrorclassBlackCat(BaseModel):pet_type:Literal['blackcat']classWhiteCat(BaseModel):pet_type:Literal['whitecat']classModel(BaseModel):cat:BlackCat|WhiteCat=Field(discriminator='pet_type')try:Model(cat={'pet_type':'dog'})exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'union_tag_invalid'

union_tag_not_found

This error is raised when it is not possible to extract a discriminator value from the input:

fromtypingimportLiteral,UnionfrompydanticimportBaseModel,Field,ValidationErrorclassBlackCat(BaseModel):pet_type:Literal['blackcat']classWhiteCat(BaseModel):pet_type:Literal['whitecat']classModel(BaseModel):cat:Union[BlackCat,WhiteCat]=Field(discriminator='pet_type')try:Model(cat={'name':'blackcat'})exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'union_tag_not_found'
fromtypingimportLiteralfrompydanticimportBaseModel,Field,ValidationErrorclassBlackCat(BaseModel):pet_type:Literal['blackcat']classWhiteCat(BaseModel):pet_type:Literal['whitecat']classModel(BaseModel):cat:BlackCat|WhiteCat=Field(discriminator='pet_type')try:Model(cat={'name':'blackcat'})exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'union_tag_not_found'

url_parsing

This error is raised when the input value cannot be parsed as a URL:

frompydanticimportAnyUrl,BaseModel,ValidationErrorclassModel(BaseModel):x:AnyUrltry:Model(x='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'url_parsing'

url_scheme

This error is raised when the URL scheme is not valid for the URL type of the field:

frompydanticimportBaseModel,HttpUrl,ValidationErrorclassModel(BaseModel):x:HttpUrltry:Model(x='ftp://example.com')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'url_scheme'

url_syntax_violation

This error is raised when the URL syntax is not valid:

frompydanticimportBaseModel,Field,HttpUrl,ValidationErrorclassModel(BaseModel):x:HttpUrl=Field(strict=True)try:Model(x='http:////example.com')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'url_syntax_violation'

url_too_long

This error is raised when the URL length is greater than 2083:

frompydanticimportBaseModel,HttpUrl,ValidationErrorclassModel(BaseModel):x:HttpUrltry:Model(x='x'*2084)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'url_too_long'

url_type

This error is raised when the input value's type is not valid for a URL field:

frompydanticimportBaseModel,HttpUrl,ValidationErrorclassModel(BaseModel):x:HttpUrltry:Model(x=None)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'url_type'

uuid_parsing

This error is raised when the input value's type is not valid for a UUID field:

fromuuidimportUUIDfrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):u:UUIDtry:Model(u='12345678-124-1234-1234-567812345678')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'uuid_parsing'

uuid_type

This error is raised when the input value's type is not valid instance for a UUID field (str, bytes or UUID):

fromuuidimportUUIDfrompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):u:UUIDtry:Model(u=1234567812412341234567812345678)exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'uuid_type'

uuid_version

This error is raised when the input value's type is not match UUID version:

frompydanticimportUUID5,BaseModel,ValidationErrorclassModel(BaseModel):u:UUID5try:Model(u='a6cc5730-2261-11ee-9c43-2eb5a363657c')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'uuid_version'

value_error

This error is raised when aValueError is raised during validation:

frompydanticimportBaseModel,ValidationError,field_validatorclassModel(BaseModel):x:str@field_validator('x')@classmethoddefrepeat_b(cls,v):raiseValueError()try:Model(x='test')exceptValidationErrorasexc:print(repr(exc.errors()[0]['type']))#> 'value_error'

[8]ページ先頭

©2009-2025 Movatter.jp