dataclasses의 dataclass를 이용해서 data를 담아두는 클래스를 생성하는 식으로 파이썬 코드를 작성중에 pydantic에 대해 알게되어 정리합니다.
데이터 검증에 널리 사용되는 라이브러리 입니다.
순수한 파이썬 3.8+ 코드로 데이터 형식을 정의하고, 유효성을 검증할 수 있습니다.
공식 문서에서는 유효성 검증 라이브러리라고 하나 원하는 타입으로 파싱을 해주는 역할이 더 크게 느껴집니다.
외부에서 config를 생성하고 해당 **config를 데이터 클래스 생성시 인자로 넘겨주면 자동으로 파싱해주기 때문에 몹시 편리합니다.
외부에서 정의한 데이터를 User 전달해보는 예제입니다.
from datetime import datetime
from pydantic import BaseModel, PositiveInt
class User(BaseModel):
id: int
name: str = 'John Doe'
signup_ts: datetime | None
tastes: dict[str, PositiveInt]
external_data = {
'id': 123,
'signup_ts': '2019-06-01 12:22',
'tastes': {
'wine': 9,
b'cheese': 7,
'cabbage': '1',
},
}
user = User(**external_data)
print(user.id)
#> 123
print(user.model_dump())
"""
{
'id': 123,
'name': 'John Doe',
'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
'tastes': {'wine': 9, 'cheese': 7, 'cabbage': 1},
}
"""
만약 검증에 실패하면 다음과 같이 ValidtationError를 일으킵니다.
# continuing the above example...
from pydantic import ValidationError
class User(BaseModel):
id: int
name: str = 'John Doe'
signup_ts: datetime | None
tastes: dict[str, PositiveInt]
external_data = {'id': 'not an int', 'tastes': {}}
try:
User(**external_data)
except ValidationError as e:
print(e.errors())
"""
[
{
'type': 'int_parsing',
'loc': ('id',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'not an int',
'url': 'https://errors.pydantic.dev/2/v/int_parsing',
},
{
'type': 'missing',
'loc': ('signup_ts',),
'msg': 'Field required',
'input': {'id': 'not an int', 'tastes': {}},
'url': 'https://errors.pydantic.dev/2/v/missing',
},
]
"""