PYTHON · 성능
Context Manager & __slots__
contextlib로 리소스를 안전하게 관리하고, __slots__로 메모리를 최적화합니다.
성능고급contextmanagersuppress__slots__메모리timer
핵심 설명
contextlib로 리소스를 안전하게 관리하고, __slots__로 메모리를 최적화합니다.
Python code
from contextlib import contextmanager, suppress
import time
# @contextmanager — 제너레이터로 컨텍스트 매니저 구현
@contextmanager
def timer(label: str):
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed:.4f}초")
with timer("작업"):
total = sum(range(1_000_000))
# suppress — 특정 예외 무시
with suppress(FileNotFoundError):
open("nonexistent.txt")
print("파일 없어도 계속 실행")
# __slots__ — 메모리 최적화
# 기본 클래스: __dict__ 사용 (동적 속성 추가 가능)
class NormalPoint:
def __init__(self, x, y):
self.x = x
self.y = y
# __slots__ 클래스: 고정 속성, 메모리 ~50% 절약
class SlottedPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
import sys
np = NormalPoint(1.0, 2.0)
sp = SlottedPoint(1.0, 2.0)
print(f"일반: {sys.getsizeof(np.__dict__)}B")
print(f"slots: (no __dict__)")
# 수백만 개 객체 생성 시 큰 차이
normal = [NormalPoint(i, i) for i in range(100_000)]
slotted = [SlottedPoint(i, i) for i in range(100_000)]학습 팁
__slots__를 사용하면 동적 속성 추가가 불가능해집니다. 데이터 컨테이너처럼 속성이 고정된 클래스에 적합합니다.
주의할 점
__slots__를 상속받은 클래스에서 __slots__를 선언하지 않으면 자동으로 __dict__가 추가되어 최적화 효과가 사라집니다.
자주 묻는 질문
Context Manager & __slots__란 무엇인가요?
contextlib 로 리소스를 안전하게 관리하고, __slots__ 로 메모리를 최적화합니다.
Context Manager & __slots__ 학습 시 주의할 점은 무엇인가요?
__slots__ 를 상속받은 클래스에서 __slots__ 를 선언하지 않으면 자동으로 __dict__ 가 추가되어 최적화 효과가 사라집니다.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.