본문 바로가기
Python

[Python] Pydantic 라이브러리 BaseModel 클래스 - 데이터 유효성 검사

by teamnova 2025. 11. 19.
728x90

안녕하세요. 

오늘은 파이썬의 Pydantic 라이브러리에 있는 BaseModel 클래스에 대해 알아보겠습니다. 

 

파이썬은 변수의 타입을 강제하지 않는 동적 타이핑 언어입니다. 

코드를 유연하게 작성하기에는 좋지만, 이로 인해 데이터 형식이 맞지 않아 런타임 에러가 발생하기도 합니다. 

 특히  API를 개발하거나 외부 데이터를 처리할 때, 데이터 형식을 확인하는 과정은 필수입니다. 

 

이럴때 Pydantic 라이브러리와 BaseModel 를 활용하여 데이터 유효성 검사를 빠르게 할 수 있습니다. 

 

BaseModel

 

BaseModel은 Pydantic라이브러리에서 데이터 모델을 정의할 때 상속받는 기본 클래스입니다. 

 

파이썬의 타입 힌트 기능을 활용하여, 클래스 속성에 타임을 명시하면 아래의 기능을 자동으로 제공합니다. 

- 데이터 유효성 검사 (Data Validation): 입력된 데이터가 지정된 타입과 맞는지 검사합니다.
- 데이터 형변환 (Data Coercion): 문자열 "123"을 정수 123으로 바꾸는 등, 가능한 경우 타입을 자동으로 변환해 줍니다.
- JSON 직렬화 (Serialization): 객체를 쉽게 JSON이나 딕셔너리 형태로 변환할 수 있습니다.

 

 

BaseModel 사용 예제

 

먼저, Pydantic 라이브러리를 설치합니다. 

pip install pydantic

 

예제 코드입니다. 

 

from pydantic import BaseModel
from typing import Optional
from pydantic import ValidationError


class User(BaseModel):
    id: int
    username: str
    email: str
    is_active: bool = True  # 기본값(default) 설정 가능
    age: Optional[int] = None # 선택적 필드 (없어도 됨)

    # 올바른 데이터로 생성
user1 = User(id=1, username="johndoe", email="john@example.com")
print(user1)
# 출력: id=1 username='johndoe' email='john@example.com' is_active=True age=None

# 형변환(Coercion) 예시
# id에 문자열 "100"을 넣었지만, int로 자동 변환됩니다.
user2 = User(id="100", username="janedoe", email="jane@example.com")
print(f"ID의 타입: {type(user2.id)}, 값: {user2.id}") 
# 출력: ID의 타입: <class 'int'>, 값: 100


#유효성 검사 실패 (ValidationError) 예시
try:
    # id에 문자를 넣어서 에러 유발
    User(id="invalid_id", username="error_user", email="error@example.com")
except ValidationError as e:
    print(e)


#딕셔너리 및 JSON 변환 (직렬화)예시
user = User(id=1, username="pythonista", email="py@test.com", age=25)

# 딕셔너리로 변환
user_dict = user.model_dump()
print(user_dict)
# {'id': 1, 'username': 'pythonista', 'email': 'py@test.com', 'is_active': True, 'age': 25}

# JSON 문자열로 변환
user_json = user.model_dump_json()
print(user_json)
# {"id":1,"username":"pythonista","email":"py@test.com","is_active":true,"age":25}

 

 

실행결과 

id=1 username='johndoe' email='john@example.com' is_active=True age=None
ID의 타입: <class 'int'>, 값: 100
1 validation error for User
id
  Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='invalid_id', input_type=str]
    For further information visit https://errors.pydantic.dev/2.12/v/int_parsing
{'id': 1, 'username': 'pythonista', 'email': 'py@test.com', 'is_active': True, 'age': 25}
{"id":1,"username":"pythonista","email":"py@test.com","is_active":true,"age":25}