PYTHON · 함수형
불변 데이터 (frozen dataclass)
frozen=True 데이터클래스와 함수형 업데이트 패턴으로 불변 데이터를 다룹니다.
함수형중급frozen불변dataclassreplace
핵심 설명
frozen=True 데이터클래스와 함수형 업데이트 패턴으로 불변 데이터를 다룹니다.
Python code
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Point:
x: float
y: float
def translate(self, dx: float, dy: float) -> "Point":
return replace(self, x=self.x + dx, y=self.y + dy)
def scale(self, factor: float) -> "Point":
return replace(self, x=self.x * factor, y=self.y * factor)
# 불변 업데이트 체인
p = Point(1, 2)
p2 = p.translate(3, 4).scale(2)
print(f"원본: {p}") # Point(x=1, y=2)
print(f"변환: {p2}") # Point(x=8, y=12)
# 불변 리스트 연산
@dataclass(frozen=True)
class TodoList:
items: tuple[str, ...]
def add(self, item: str) -> "TodoList":
return TodoList(self.items + (item,))
def remove(self, item: str) -> "TodoList":
return TodoList(tuple(i for i in self.items if i != item))
todos = TodoList(()).add("공부").add("운동").add("독서")
print(todos) # TodoList(items=('공부', '운동', '독서'))
print(todos.remove("운동")) # TodoList(items=('공부', '독서'))
print(todos) # 원본 변경 없음학습 팁
dataclasses.replace()로 특정 필드만 변경한 새 인스턴스를 만들 수 있습니다.
주의할 점
frozen=True라도 내부에 mutable 객체(리스트)가 있으면 그 내용은 변경 가능합니다. 튜플을 사용하세요.
자주 묻는 질문
불변 데이터 (frozen dataclass)란 무엇인가요?
frozen=True 데이터클래스와 함수형 업데이트 패턴으로 불변 데이터를 다룹니다.
불변 데이터 (frozen dataclass) 학습 시 주의할 점은 무엇인가요?
frozen=True 라도 내부에 mutable 객체(리스트)가 있으면 그 내용은 변경 가능합니다. 튜플을 사용하세요.