콘텐츠로 이동

검증 오류

Pydantic은 유용한 유효성 검사 오류를 제공하려고 시도합니다. 다음은 pydantic을 사용할 때 사용자가 겪을 수 있는 일반적인 유효성 검사 오류에 대한 세부 정보와 이를 해결하는 방법에 대한 몇 가지 제안 사항입니다.

인수_유형

이 오류는 유효성 검사 중에 함수에 인수로 전달되는 객체가 tuple , list 또는 dict 아닐 때 발생합니다. NamedTuple 구현 시 함수 호출을 사용하기 때문에 이것이 이 오류를 생성하는 한 가지 방법입니다.

from typing import NamedTuple

from pydantic import BaseModel, ValidationError


class MyNamedTuple(NamedTuple):
    x: int


class MyModel(BaseModel):
    field: MyNamedTuple


try:
    MyModel.model_validate({'field': 'invalid'})
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'arguments_type'

주장_오류

이 오류는 유효성 검사 중에 실패한 assert 문이 발견되면 발생합니다.

from pydantic import BaseModel, ValidationError, field_validator


class Model(BaseModel):
    x: int

    @field_validator('x')
    @classmethod
    def force_x_positive(cls, v):
        assert v > 0
        return v


try:
    Model(x=-1)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'assertion_error'

bool_parsing

이 오류는 입력 값이 부울로 강제 변환하는 데 유효하지 않은 문자열인 경우 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: bool


Model(x='true')  # OK

try:
    Model(x='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'bool_parsing'

bool_type

이 오류는 입력 값의 유형이 bool 필드에 대해 유효하지 않을 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: bool


try:
    Model(x=None)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'bool_type'

입력 값이 bool 의 인스턴스가 아닌 경우 엄격한 필드에 대해서도 이 오류가 발생합니다.

bytes_too_long

이 오류는 bytes 값의 길이가 필드의 max_length 제약 조건보다 클 때 발생합니다.

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: bytes = Field(max_length=3)


try:
    Model(x=b'test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'bytes_too_long'

bytes_too_short

이 오류는 bytes 값의 길이가 필드의 min_length 제약 조건보다 작을 때 발생합니다.

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: bytes = Field(min_length=3)


try:
    Model(x=b't')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'bytes_too_short'

bytes_type

이 오류는 입력 값의 유형이 bytes 필드에 유효하지 않을 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: bytes


try:
    Model(x=123)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'bytes_type'

이 오류는 입력 값이 bytes 의 인스턴스가 아닌 경우 엄격한 필드에 대해서도 발생합니다.

callable_type

이 오류는 입력 값이 Callable 로 유효하지 않을 때 발생합니다.

from typing import Any, Callable

from pydantic import BaseModel, ImportString, ValidationError


class Model(BaseModel):
    x: ImportString[Callable[[Any], Any]]


Model(x='math:cos')  # OK

try:
    Model(x='os.path')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'callable_type'

dataclass_exact_type

이 오류는 strict=True 로 데이터 클래스를 검증할 때 입력이 데이터 클래스의 인스턴스가 아닐 때 발생합니다.

import pydantic.dataclasses
from pydantic import TypeAdapter, ValidationError


@pydantic.dataclasses.dataclass
class MyDataclass:
    x: str


adapter = 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)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'dataclass_exact_type'

dataclass_type

이 오류는 dataclass 필드에 대한 입력 값이 유효하지 않을 때 발생합니다.

from pydantic import ValidationError, dataclasses


@dataclasses.dataclass
class Inner:
    x: int


@dataclasses.dataclass
class Outer:
    y: Inner


Outer(y=Inner(x=1))  # OK

try:
    Outer(y=1)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'dataclass_type'

date_from_datetime_inexact

이 오류는 date 필드에 제공된 입력 datetime 값에 0이 아닌 시간 구성 요소가 있는 경우 발생합니다. 타임스탬프를 date 유형의 필드로 구문 분석하려면 시간 구성 요소가 모두 0이어야 합니다.

from datetime import date, datetime

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: date


Model(x='2023-01-01')  # OK
Model(x=datetime(2023, 1, 1))  # OK

try:
    Model(x=datetime(2023, 1, 1, 12))
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'date_from_datetime_inexact'

date_from_datetime_parsing

이 오류는 입력 값이 date 필드에 대해 구문 분석할 수 없는 문자열인 경우 발생합니다.

from datetime import date

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: date


try:
    Model(x='XX1494012000')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'date_from_datetime_parsing'

date_future

이 오류는 FutureDate 필드에 제공된 입력 값이 미래가 아닐 때 발생합니다.

from datetime import date

from pydantic import BaseModel, FutureDate, ValidationError


class Model(BaseModel):
    x: FutureDate


try:
    Model(x=date(2000, 1, 1))
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'date_future'

date_parsing

이 오류는 입력 값이 date 필드에 대해 구문 분석할 수 없는 문자열인 JSON을 검증할 때 발생합니다.

import json
from datetime import date

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: date = Field(strict=True)


try:
    Model.model_validate_json(json.dumps({'x': '1'}))
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'date_parsing'

date_past

이 오류는 PastDate 필드에 제공된 값이 과거가 아닐 때 발생합니다.

from datetime import date, timedelta

from pydantic import BaseModel, PastDate, ValidationError


class Model(BaseModel):
    x: PastDate


try:
    Model(x=date.today() + timedelta(1))
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'date_past'

date_type

이 오류는 입력 값의 유형이 date 필드에 유효하지 않을 때 발생합니다.

from datetime import date

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: date


try:
    Model(x=None)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'date_type'

입력 값이 date 의 인스턴스가 아닌 경우 엄격한 필드에 대해서도 이 오류가 발생합니다.

datetime_from_date_parsing

!!! note 이 오류에 대한 지원은 yyyy-MM-DD 날짜의 날짜/시간 구문 분석 지원과 함께 v2.6.0 에 추가될 예정입니다.

이 오류는 입력 값이 datetime 필드에 대해 구문 분석할 수 없는 문자열인 경우 발생합니다.

from datetime import datetime

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: datetime


try:
    # there is no 13th month
    Model(x='2023-13-01')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'datetime_from_date_parsing'

datetime_future

이 오류는 FutureDatetime 필드에 제공된 값이 미래가 아닐 때 발생합니다.

from datetime import datetime

from pydantic import BaseModel, FutureDatetime, ValidationError


class Model(BaseModel):
    x: FutureDatetime


try:
    Model(x=datetime(2000, 1, 1))
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'datetime_future'

datetime_object_invalid

이 오류는 datetime 객체에 대한 내용이 유효하지 않을 때 발생합니다.

from datetime import datetime, tzinfo

from pydantic import AwareDatetime, BaseModel, ValidationError


class CustomTz(tzinfo):
    # utcoffset is not implemented!

    def tzname(self, _dt):
        return 'CustomTZ'


class Model(BaseModel):
    x: AwareDatetime


try:
    Model(x=datetime(2023, 1, 1, tzinfo=CustomTz()))
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'datetime_object_invalid'

datetime_parsing

이 오류는 값이 datetime 필드에 대해 구문 분석할 수 없는 문자열인 경우 발생합니다.

import json
from datetime import datetime

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: datetime = Field(strict=True)


try:
    Model.model_validate_json(json.dumps({'x': 'not a datetime'}))
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'datetime_parsing'

datetime_past

이 오류는 PastDatetime 필드에 제공된 값이 과거가 아닐 때 발생합니다.

from datetime import datetime, timedelta

from pydantic import BaseModel, PastDatetime, ValidationError


class Model(BaseModel):
    x: PastDatetime


try:
    Model(x=datetime.now() + timedelta(100))
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'datetime_past'

datetime_type

이 오류는 입력 값의 유형이 datetime 필드에 유효하지 않을 때 발생합니다.

from datetime import datetime

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: datetime


try:
    Model(x=None)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'datetime_type'

입력 값이 datetime 의 인스턴스가 아닌 경우 엄격한 필드에 대해서도 이 오류가 발생합니다.

decimal_max_digits

이 오류는 Decimal 에 제공된 값의 자릿수가 너무 많으면 발생합니다.

from decimal import Decimal

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: Decimal = Field(max_digits=3)


try:
    Model(x='42.1234')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'decimal_max_digits'

decimal_max_places

이 오류는 Decimal 에 제공된 값의 소수점 이하 자릿수가 너무 많으면 발생합니다.

from decimal import Decimal

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: Decimal = Field(decimal_places=3)


try:
    Model(x='42.1234')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'decimal_max_places'

decimal_parsing

이 오류는 Decimal 에 제공된 값을 10진수로 구문 분석할 수 없을 때 발생합니다.

from decimal import Decimal

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: Decimal = Field(decimal_places=3)


try:
    Model(x='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'decimal_parsing'

decimal_type

이 오류는 Decimal 에 제공된 값이 잘못된 유형일 때 발생합니다.

from decimal import Decimal

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: Decimal = Field(decimal_places=3)


try:
    Model(x=[1, 2, 3])
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'decimal_type'

입력 값이 Decimal 의 인스턴스가 아닌 경우 엄격한 필드에 대해서도 이 오류가 발생합니다.

decimal_whole_digits

이 오류는 Decimal 에 제공된 값이 max_digits - decimal_places (두 가지 모두 지정되는 경우)보다 소수점 앞의 자릿수가 더 많은 경우 발생합니다.

from decimal import Decimal

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: Decimal = Field(max_digits=6, decimal_places=3)


try:
    Model(x='12345.6')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'decimal_whole_digits'

입력 값이 Decimal 의 인스턴스가 아닌 경우 엄격한 필드에 대해서도 이 오류가 발생합니다.

dict_type

이 오류는 입력 값의 유형이 dict 필드에 대한 dict 가 아닐 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: dict


try:
    Model(x=['1', '2'])
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'dict_type'

enum

이 오류는 열거 enum 필드 멤버에 입력 값이 없을 때 발생합니다.

from enum import Enum

from pydantic import BaseModel, ValidationError


class MyEnum(str, Enum):
    option = 'option'


class Model(BaseModel):
    x: MyEnum


try:
    Model(x='other_option')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'enum'

extra_forbidden

이 오류는 입력 값에 추가 필드가 포함되어 있을 때 발생하지만 model_config['extra'] == 'forbid' :

from pydantic import BaseModel, ConfigDict, ValidationError


class Model(BaseModel):
    x: str

    model_config = ConfigDict(extra='forbid')


try:
    Model(x='test', y='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'extra_forbidden'

추가 속성 섹션에서 extra 구성에 대한 자세한 내용을 읽을 수 있습니다.

finite_number

이 오류는 값이 무한하거나 유효성 검사 중에 64비트 부동 소수점 숫자로 표시하기에는 너무 큰 경우 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: int


try:
    Model(x=2.2250738585072011e308)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'finite_number'

float_parsing

이 오류는 값이 float 로 구문 분석될 수 없는 문자열인 경우 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: float


try:
    Model(x='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'float_parsing'

float_type

이 오류는 입력 값의 유형이 float 필드에 유효하지 않을 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: float


try:
    Model(x=None)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'float_type'

frozen_field

이 오류는 frozen=True 인 필드에 값을 할당하려고 하거나 해당 필드를 삭제하려고 할 때 발생합니다.

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: str = Field('test', frozen=True)


model = Model()

try:
    model.x = 'test1'
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'frozen_field'

try:
    del model.x
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'frozen_field'

frozen_instance

이 오류는 model_config['frozen] == True 이고 필드에 새 값을 삭제하거나 할당하려고 하면 발생합니다.

from pydantic import BaseModel, ConfigDict, ValidationError


class Model(BaseModel):
    x: int

    model_config = ConfigDict(frozen=True)


m = Model(x=1)

try:
    m.x = 2
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'frozen_instance'

try:
    del m.x
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'frozen_instance'

frozen_set_type

이 오류는 입력 값 유형이 frozenset 필드에 유효하지 않을 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: frozenset


try:
    model = Model(x='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'frozen_set_type'

get_attribute_error

이 오류는 다음과 같은 경우에 발생합니다. model_config['from_attributes'] == True 속성을 읽는 동안 오류가 발생합니다.

from pydantic import BaseModel, ConfigDict, ValidationError


class Foobar:
    def __init__(self):
        self.x = 1

    @property
    def y(self):
        raise RuntimeError('intentional error')


class Model(BaseModel):
    x: int
    y: str

    model_config = ConfigDict(from_attributes=True)


try:
    Model.model_validate(Foobar())
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'get_attribute_error'

greater_than

이 오류는 값이 필드의 gt 제약 조건보다 크지 않을 때 발생합니다.

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: int = Field(gt=10)


try:
    Model(x=10)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'greater_than'

greater_than_equal

이 오류는 값이 필드의 ge 제약 조건보다 크거나 같지 않을 때 발생합니다.

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: int = Field(ge=10)


try:
    Model(x=9)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'greater_than_equal'

int_from_float

이 오류는 int 필드에 float 값을 제공할 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: int


try:
    Model(x=0.5)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'int_from_float'

int_parsing

이 오류는 값을 int 로 구문 분석할 수 없을 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: int


try:
    Model(x='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'int_parsing'

int_parsing_size

이 오류는 Python str 에서 int 구문 분석이 허용하는 최대 범위를 벗어난 문자열에서 Python 또는 JSON 값을 구문 분석하려고 할 때 발생합니다.

import json

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: int


# from Python
assert Model(x='1' * 4_300).x == int('1' * 4_300)  # OK

too_long = '1' * 4_301
try:
    Model(x=too_long)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'int_parsing_size'

# from JSON
try:
    Model.model_validate_json(json.dumps({'x': too_long}))
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'int_parsing_size'

int_type

이 오류는 입력 값의 유형이 int 필드에 유효하지 않을 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: int


try:
    Model(x=None)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'int_type'

invalid_key

이 오류는 str 인스턴스가 아닌 키가 있는 dict 의 유효성을 검사하려고 할 때 발생합니다.

from pydantic import BaseModel, ConfigDict, ValidationError


class Model(BaseModel):
    x: int

    model_config = ConfigDict(extra='allow')


try:
    Model.model_validate({'x': 1, b'y': 2})
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'invalid_key'

is_instance_of

이 오류는 입력 값이 예상 유형의 인스턴스가 아닐 때 발생합니다.

from pydantic import BaseModel, ConfigDict, ValidationError


class Nested:
    x: str


class Model(BaseModel):
    y: Nested

    model_config = ConfigDict(arbitrary_types_allowed=True)


try:
    Model(y='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'is_instance_of'

is_subclass_of

이 오류는 입력 값이 예상 유형의 하위 클래스가 아닐 때 발생합니다.

from typing import Type

from pydantic import BaseModel, ValidationError


class Nested:
    x: str


class Model(BaseModel):
    y: Type[Nested]


try:
    Model(y='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'is_subclass_of'

iterable_type

이 오류는 입력 값이 Iterable 로 유효하지 않을 때 발생합니다.

from typing import Iterable

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    y: Iterable


try:
    Model(y=123)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'iterable_type'

iteration_error

이 오류는 반복 중에 오류가 발생하면 발생합니다.

from typing import List

from pydantic import BaseModel, ValidationError


def gen():
    yield 1
    raise RuntimeError('error')


class Model(BaseModel):
    x: List[int]


try:
    Model(x=gen())
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'iteration_error'

json_invalid

이 오류는 입력 값이 유효한 JSON 문자열이 아닌 경우 발생합니다.

from pydantic import BaseModel, Json, ValidationError


class Model(BaseModel):
    x: Json


try:
    Model(x='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'json_invalid'

json_type

이 오류는 입력 값이 JSON으로 구문 분석할 수 없는 유형일 때 발생합니다.

from pydantic import BaseModel, Json, ValidationError


class Model(BaseModel):
    x: Json


try:
    Model(x=None)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'json_type'

less_than

이 오류는 입력 값이 필드의 lt 제약 조건보다 작지 않을 때 발생합니다.

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: int = Field(lt=10)


try:
    Model(x=10)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'less_than'

less_than_equal

이 오류는 입력 값이 필드의 le 조건보다 작거나 같을 때 발생합니다.

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: int = Field(le=10)


try:
    Model(x=11)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'less_than_equal'

list_type

이 오류는 입력 값 유형이 list 필드에 유효하지 않을 때 발생합니다.

from typing import List

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: List[int]


try:
    Model(x=1)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'list_type'

literal_error

이 오류는 입력 값이 예상 리터럴 값 중 하나가 아닌 경우 발생합니다.

from typing_extensions import Literal

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: Literal['a', 'b']


Model(x='a')  # OK

try:
    Model(x='c')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'literal_error'

mapping_type

이 오류는 .items() 와 같은 Mapping 프로토콜의 메서드 호출 실패로 인해 유효성 검사 중에 문제가 발생할 때 발생합니다.

from collections.abc import Mapping
from typing import Dict

from pydantic import BaseModel, ValidationError


class BadMapping(Mapping):
    def items(self):
        raise ValueError()

    def __iter__(self):
        raise ValueError()

    def __getitem__(self, key):
        raise ValueError()

    def __len__(self):
        return 1


class Model(BaseModel):
    x: Dict[str, str]


try:
    Model(x=BadMapping())
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'mapping_type'

missing

이 오류는 입력 값에 필수 필드가 누락된 경우 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: str


try:
    Model()
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'missing'

missing_argument

이 오류는 필요한 위치 또는 키워드 인수가 validate_call 로 장식된 함수에 전달되지 않을 때 발생합니다.

from pydantic import ValidationError, validate_call


@validate_call
def foo(a: int):
    return a


try:
    foo()
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'missing_argument'

missing_keyword_only_argument

이 오류는 필수 키워드 전용 인수가 validate_call 로 장식된 함수에 전달되지 않을 때 발생합니다.

from pydantic import ValidationError, validate_call


@validate_call
def foo(*, a: int):
    return a


try:
    foo()
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'missing_keyword_only_argument'

missing_positional_only_argument

이 오류는 validate_call 로 데코레이트된 함수에 필수 위치 전용 인수가 전달되지 않을 때 발생합니다.

from pydantic import ValidationError, validate_call


@validate_call
def foo(a: int, /):
    return a


try:
    foo()
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'missing_positional_only_argument'

model_attributes_type

이 오류는 입력 값이 유효한 사전, 모델 인스턴스 또는 필드를 추출할 수 있는 인스턴스가 아닐 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    a: int
    b: int


# simply validating a dict
print(Model.model_validate({'a': 1, 'b': 2}))
#> a=1 b=2


class CustomObj:
    def __init__(self, a, b):
        self.a = a
        self.b = b


# using from attributes to extract fields from an objects
print(Model.model_validate(CustomObj(3, 4), from_attributes=True))
#> a=3 b=4

try:
    Model.model_validate('not an object', from_attributes=True)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'model_attributes_type'

model_type

이 오류는 모델에 대한 입력이 모델이나 사전의 인스턴스가 아닐 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    a: int
    b: int


# simply validating a dict
m = Model.model_validate({'a': 1, 'b': 2})
print(m)
#> a=1 b=2

# validating an existing model instance
print(Model.model_validate(m))
#> a=1 b=2

try:
    Model.model_validate('not an object')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'model_type'

multiple_argument_values

이 오류는 validate_call 로 장식된 함수를 호출하는 동안 단일 인수에 대해 여러 값을 제공할 때 발생합니다.

from pydantic import ValidationError, validate_call


@validate_call
def foo(a: int):
    return a


try:
    foo(1, a=2)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'multiple_argument_values'

multiple_of

이 오류는 입력이 필드의 multiple_of 제약 조건의 배수가 아닌 경우 발생합니다.

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: int = Field(multiple_of=5)


try:
    Model(x=1)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'multiple_of'

no_such_attribute

이 오류는 구성에서 validate_assignment=True 이고 기존 필드가 아닌 속성에 값을 할당하려고 할 때 발생합니다.

from pydantic import ConfigDict, ValidationError, dataclasses


@dataclasses.dataclass(config=ConfigDict(validate_assignment=True))
class MyDataclass:
    x: int


m = MyDataclass(x=1)
try:
    m.y = 10
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'no_such_attribute'

none_required

이 오류는 None 필요한 필드에 대해 입력 값이 None 아닐 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: None


try:
    Model(x=1)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'none_required'

!!! note 모델의 필드 이름과 해당 유형 사이에 이름 충돌이 있는 경우 이 오류가 발생할 수 있습니다. 더 구체적으로 말하면, 해당 필드의 기본값이 None 인 경우 이 오류가 발생할 가능성이 높습니다.

For example, the following would yield the `none_required` validation error since the field `int` is set to a default value of `None` and has the exact same name as its type, which causes problems with validation.
```py
from typing import Optional

from pydantic import BaseModel


class M1(BaseModel):
    int: Optional[int] = None


m = M1(int=123)  # errors
```

recursion_loop

이 오류는 순환 참조가 감지되면 발생합니다.

from typing import List

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: List['Model']


d = {'x': []}
d['x'].append(d)
try:
    Model(**d)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'recursion_loop'

set_type

이 오류는 값 유형이 set 필드에 유효하지 않을 때 발생합니다.

from typing import Set

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: Set[int]


try:
    Model(x='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'set_type'

string_pattern_mismatch

이 오류는 입력 값이 필드의 pattern 제약 조건과 일치하지 않을 때 발생합니다.

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: str = Field(pattern='test')


try:
    Model(x='1')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'string_pattern_mismatch'

string_sub_type

이 오류는 필드가 엄격할 때 값이 str 의 엄격한 하위 유형의 인스턴스일 때 발생합니다.

from enum import Enum

from pydantic import BaseModel, Field, ValidationError


class MyEnum(str, Enum):
    foo = 'foo'


class Model(BaseModel):
    x: str = Field(strict=True)


try:
    Model(x=MyEnum.foo)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'string_sub_type'

string_too_long

이 오류는 입력 값이 길이가 필드의 max_length 제약 조건보다 큰 문자열인 경우 발생합니다.

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: str = Field(max_length=3)


try:
    Model(x='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'string_too_long'

string_too_short

이 오류는 입력 값이 길이가 필드의 min_length 제약 조건보다 작은 문자열인 경우 발생합니다.

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: str = Field(min_length=3)


try:
    Model(x='t')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'string_too_short'

string_type

이 오류는 입력 값의 유형이 str 필드에 유효하지 않을 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: str


try:
    Model(x=1)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'string_type'

입력 값이 str 의 인스턴스가 아닌 경우 엄격한 필드에 대해서도 이 오류가 발생합니다.

string_unicode

이 오류는 값을 유니코드 문자열로 구문 분석할 수 없을 때 발생합니다.

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: str


try:
    Model(x=b'\x81')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'string_unicode'

time_delta_parsing

이 오류는 입력 값이 timedelta 필드에 대해 구문 분석할 수 없는 문자열인 경우 발생합니다.

from datetime import timedelta

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: timedelta


try:
    Model(x='t')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'time_delta_parsing'

time_delta_type

이 오류는 입력 값의 유형이 timedelta 필드에 유효하지 않을 때 발생합니다.

from datetime import timedelta

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: timedelta


try:
    Model(x=None)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'time_delta_type'

입력 값이 timedelta 의 인스턴스가 아닌 경우 엄격한 필드에 대해서도 이 오류가 발생합니다.

time_parsing

이 오류는 입력 값이 time 필드에 대해 구문 분석할 수 없는 문자열인 경우 발생합니다.

from datetime import time

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: time


try:
    Model(x='25:20:30.400')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'time_parsing'

time_type

이 오류는 time 필드에 대한 값 유형이 유효하지 않을 때 발생합니다.

from datetime import time

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: time


try:
    Model(x=None)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'time_type'

이 오류는 입력 값이 time 인스턴스가 아닌 엄격한 필드에 대해서도 발생합니다.

timezone_aware

이 오류는 시간대 인식 날짜/ datetime 필드에 제공된 datetime 값에 시간대 정보가 없을 때 발생합니다.

from datetime import datetime

from pydantic import AwareDatetime, BaseModel, ValidationError


class Model(BaseModel):
    x: AwareDatetime


try:
    Model(x=datetime.now())
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'timezone_aware'

timezone_naive

이 오류는 시간대 기반 날짜/ datetime 필드에 제공된 datetime 값에 시간대 정보가 있는 경우 발생합니다.

from datetime import datetime, timezone

from pydantic import BaseModel, NaiveDatetime, ValidationError


class Model(BaseModel):
    x: NaiveDatetime


try:
    Model(x=datetime.now(tz=timezone.utc))
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'timezone_naive'

too_long

이 오류는 입력 값의 길이가 필드의 max_length 제약 조건보다 클 때 발생합니다.

from typing import List

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: List[int] = Field(max_length=3)


try:
    Model(x=[1, 2, 3, 4])
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'too_long'

too_short

이 오류는 값 길이가 필드의 min_length 제약 조건보다 작을 때 발생합니다.

from typing import List

from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
    x: List[int] = Field(min_length=3)


try:
    Model(x=[1, 2])
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'too_short'

tuple_type

이 오류는 입력 값의 유형이 tuple 필드에 유효하지 않을 때 발생합니다.

from typing import Tuple

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    x: Tuple[int]


try:
    Model(x=None)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'tuple_type'

이 오류는 입력 값이 tuple 의 인스턴스가 아닌 경우 엄격한 필드에 대해서도 발생합니다.

unexpected_keyword_argument

이 오류는 validate_call 로 장식된 함수를 호출하는 동안 위치 전용 인수에 대해 키워드로 값을 제공할 때 발생합니다.

from pydantic import ValidationError, validate_call


@validate_call
def foo(a: int, /):
    return a


try:
    foo(a=2)
except ValidationError as exc:
    print(repr(exc.errors()[1]['type']))
    #> 'unexpected_keyword_argument'

pydantic.dataclasses 및 extra=forbid 사용할 때도 발생합니다.

from pydantic import TypeAdapter, ValidationError
from pydantic.dataclasses import dataclass


@dataclass(config={'extra': 'forbid'})
class Foo:
    bar: int


try:
    TypeAdapter(Foo).validate_python({'bar': 1, 'foobar': 2})
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'unexpected_keyword_argument'

unexpected_positional_argument

이 오류는 validate_call 로 장식된 함수를 호출하는 동안 키워드 전용 인수에 대한 위치 값을 제공할 때 발생합니다.

from pydantic import ValidationError, validate_call


@validate_call
def foo(*, a: int):
    return a


try:
    foo(2)
except ValidationError as exc:
    print(repr(exc.errors()[1]['type']))
    #> 'unexpected_positional_argument'

union_tag_invalid

이 오류는 입력의 판별자가 예상 값 중 하나가 아닐 때 발생합니다.

from typing import Union

from typing_extensions import Literal

from pydantic import BaseModel, Field, ValidationError


class BlackCat(BaseModel):
    pet_type: Literal['blackcat']


class WhiteCat(BaseModel):
    pet_type: Literal['whitecat']


class Model(BaseModel):
    cat: Union[BlackCat, WhiteCat] = Field(..., discriminator='pet_type')


try:
    Model(cat={'pet_type': 'dog'})
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'union_tag_invalid'

union_tag_not_found

이 오류는 입력에서 판별자 값을 추출할 수 없을 때 발생합니다.

from typing import Union

from typing_extensions import Literal

from pydantic import BaseModel, Field, ValidationError


class BlackCat(BaseModel):
    pet_type: Literal['blackcat']


class WhiteCat(BaseModel):
    pet_type: Literal['whitecat']


class Model(BaseModel):
    cat: Union[BlackCat, WhiteCat] = Field(..., discriminator='pet_type')


try:
    Model(cat={'name': 'blackcat'})
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'union_tag_not_found'

url_parsing

이 오류는 입력 값을 URL로 구문 분석할 수 없을 때 발생합니다.

from pydantic import AnyUrl, BaseModel, ValidationError


class Model(BaseModel):
    x: AnyUrl


try:
    Model(x='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'url_parsing'

url_scheme

이 오류는 필드의 URL 유형에 대해 URL 구성표가 유효하지 않을 때 발생합니다.

from pydantic import BaseModel, HttpUrl, ValidationError


class Model(BaseModel):
    x: HttpUrl


try:
    Model(x='ftp://example.com')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'url_scheme'

url_syntax_violation

이 오류는 URL 구문이 유효하지 않을 때 발생합니다.

from pydantic import BaseModel, Field, HttpUrl, ValidationError


class Model(BaseModel):
    x: HttpUrl = Field(strict=True)


try:
    Model(x='http:////example.com')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'url_syntax_violation'

url_too_long

이 오류는 URL 길이가 2083보다 길 때 발생합니다.

from pydantic import BaseModel, HttpUrl, ValidationError


class Model(BaseModel):
    x: HttpUrl


try:
    Model(x='x' * 2084)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'url_too_long'

url_type

이 오류는 입력 값 유형이 URL 필드에 유효하지 않을 때 발생합니다.

from pydantic import BaseModel, HttpUrl, ValidationError


class Model(BaseModel):
    x: HttpUrl


try:
    Model(x=None)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'url_type'

uuid_parsing

이 오류는 입력 값 유형이 UUID 필드에 유효하지 않을 때 발생합니다.

from uuid import UUID

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    u: UUID


try:
    Model(u='12345678-124-1234-1234-567812345678')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'uuid_parsing'

uuid_type

이 오류는 입력 값의 유형이 UUID 필드(str, bytes 또는 UUID)에 대한 유효한 인스턴스가 아닐 때 발생합니다.

from uuid import UUID

from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    u: UUID


try:
    Model(u=1234567812412341234567812345678)
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'uuid_type'

uuid_version

이 오류는 입력 값의 유형이 UUID 버전과 일치하지 않을 때 발생합니다.

from pydantic import UUID5, BaseModel, ValidationError


class Model(BaseModel):
    u: UUID5


try:
    Model(u='a6cc5730-2261-11ee-9c43-2eb5a363657c')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'uuid_version'

value_error

이 오류는 유효성 검사 중에 ValueError 발생하면 발생합니다.

from pydantic import BaseModel, ValidationError, field_validator


class Model(BaseModel):
    x: str

    @field_validator('x')
    @classmethod
    def repeat_b(cls, v):
        raise ValueError()


try:
    Model(x='test')
except ValidationError as exc:
    print(repr(exc.errors()[0]['type']))
    #> 'value_error'

本文总阅读量