[Python] pydantic이 뭐죠?

devhans·2024년 6월 27일

Python

목록 보기
2/8
post-thumbnail

배경

dataclasses의 dataclass를 이용해서 data를 담아두는 클래스를 생성하는 식으로 파이썬 코드를 작성중에 pydantic에 대해 알게되어 정리합니다.

도입 이유

  • type hint를 통해 구동합니다.
  • rust로 작성되어 가장 빠른 데이터 유효성 검사 라이브러리 중 하나입니다.
  • json 스키마를 생성할 수 있습니다.
  • strict에 따라 데이터 변환여부를 설정할 수 있습니다.
  • Dataclasses 와 TypedDict등 많은 표준 라이브러리의 유효성 검사를 지원합니다.
  • 사용자 정의 유효성 검사와 직렬화를 지원합니다.
  • 사용자가 많고 생태계가 잘 구축된 상태입니다.

그래서 그게 뭐죠?

데이터 검증에 널리 사용되는 라이브러리 입니다.
순수한 파이썬 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',
        },
    ]
    """
profile
책 읽고 운동하기

0개의 댓글