Python 데이터클래스(dataclass)는 Python 3.7+에서 도입된 데이터 보관용 클래스를 간결하게 정의하는 데코레이터다. __init__, __repr__, __eq__ 등 보일러플레이트 메서드를 자동 생성한다.
기본 사용법
python
from dataclasses import dataclass, field
from typing import List
@dataclass
class Point:
x: float
y: float
z: float = 0.0 # 기본값
p = Point(1.0, 2.0)
print(p) # Point(x=1.0, y=2.0, z=0.0)
print(p == Point(1.0, 2.0)) # True (자동 __eq__)
field() 함수
python
@dataclass
class Inventory:
name: str
items: List[str] = field(default_factory=list) # 가변 기본값
_internal: int = field(default=0, repr=False, compare=False)
# post_init으로 검증
def __post_init__(self):
if not self.name:
raise ValueError("이름은 필수입니다")
frozen, order, slots 옵션
python
# frozen=True: 불변 (hashable)
@dataclass(frozen=True)
class Color:
r: int; g: int; b: int
c = Color(255, 0, 0)
# c.r = 100 # FrozenInstanceError
# order=True: <, <=, >, >= 자동 구현
@dataclass(order=True)
class Version:
sort_index: int = field(init=False, repr=False)
major: int
minor: int
patch: int
def __post_init__(self):
self.sort_index = self.major * 10000 + self.minor * 100 + self.patch
# slots=True (Python 3.10+): __slots__ 자동 생성
@dataclass(slots=True)
class FastPoint:
x: float
y: float
dataclass vs NamedTuple vs dict
| 특성 | dataclass | NamedTuple | dict |
|---|
| 타입 힌트 | O | O | X |
| 가변성 | 기본 가변 | 불변 | 가변 |
| 상속 | O | 제한적 | X |
| 메서드 추가 | O | O | X |
| 성능 | 보통 | 빠름 | 빠름 |
관련 개념