learn

Pydantic이란

Pydantic이란

한 줄 정의

Python type hint로 데이터 구조를 정의하면, 런타임에 자동으로 검증하고 변환해주는 라이브러리.

C struct와의 비교

개념적으로 struct와 유사하지만 차이가 있다.

C struct는 "이 필드들이 이 타입으로 존재한다"는 메모리 레이아웃 선언이다. 검증은 없고 그냥 담는 그릇.

Pydantic BaseModel은 거기에 검증 + 변환 + 직렬화가 붙은 것이다.

from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int

User(name="alice", age="25")   # "25" → 25 자동 변환
User(name="alice", age="hi")   # ValidationError
user.model_dump()              # {"name": "alice", "age": 25} JSON 직렬화

C++로 치면 struct보다는 생성자에서 타입 체크하고 변환까지 해주는 클래스에 더 가깝다.

Python dataclass와의 차이

Python에도 struct에 가까운 dataclass가 있다. 그런데 dataclass는 검증이 없다. Pydantic은 거기서 한 단계 더 나간 것.

| | dataclass | Pydantic BaseModel | |---|---|---| | 필드 선언 | ✅ | ✅ | | 런타임 타입 검증 | ❌ | ✅ | | 자동 타입 변환 | ❌ | ✅ | | 직렬화 | ❌ | ✅ |

왜 필요한가

Python은 기본적으로 type hint가 있어도 런타임에 강제하지 않는다:

def greet(name: str):
    print(f"hello {name}")

greet(12345)  # 에러 없이 그냥 실행됨

외부에서 데이터가 들어오는 상황 — API 요청, 환경변수, JSON 파싱 — 에서 이게 문제가 된다. Pydantic은 이걸 런타임에 실제로 막아준다.

pydantic-settings

what-to-centralize-imports|공통화 대상으로 소개된 pydantic-settings는 Pydantic을 환경변수에 적용한 것이다:

from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    db_url: str
    port: int = 8080

settings = Settings()  # .env 읽고, 타입 검증하고, 객체로 만들어줌

위상

FastAPI가 Pydantic을 기반으로 만들어졌을 만큼 Python 생태계에서 사실상 표준 검증 라이브러리다.