반응형
cached_property
는 속성의 결과를 캐싱하여, 속성이 여러 번 호출될 때마다 매번 계산하지 않고 처음 계산된 값을 재사용하도록 하는 유용한 데코레이터입니다. Python 3.8 이상에서는 functools
모듈의 cached_property
를 사용할 수 있습니다. 그 이전 버전에서는 werkzeug
라이브러리에서 제공하는 cached_property
를 사용할 수 있습니다.
기본 사용 방법 (functools.cached_property
)
Python 3.8 이상에서 functools
의 cached_property
를 사용하는 예제는 다음과 같습니다:
from functools import cached_property
class MyClass:
def __init__(self, value):
self.value = value
@cached_property
def computed_property(self):
print("Computing the property value...")
return self.value ** 2
# 사용 예시
obj = MyClass(10)
print(obj.computed_property) # 첫 번째 호출: "Computing the property value..." 출력, 결과 반환
print(obj.computed_property) # 두 번째 호출: 캐싱된 결과를 반환하므로 계산 없이 결과만 반환
위 코드에서 computed_property
는 처음 호출될 때 계산된 후, 그 결과가 캐시됩니다. 이후 호출부터는 저장된 값을 그대로 반환하므로, 메서드 호출 시 계산 비용이 절감됩니다.
Python 3.8 미만에서 werkzeug.cached_property
사용
Python 3.8 미만에서는 werkzeug
패키지를 사용하여 cached_property
를 구현할 수 있습니다:
werkzeug
설치:
pip install werkzeug
- 사용 예시:
from werkzeug.utils import cached_property
class MyClass:
def __init__(self, value):
self.value = value
@cached_property
def computed_property(self):
print("Computing the property value...")
return self.value ** 2
# 사용 예시
obj = MyClass(10)
print(obj.computed_property) # 첫 번째 호출: "Computing the property value..." 출력, 결과 반환
print(obj.computed_property) # 두 번째 호출: 캐싱된 결과를 반환
cached_property
가 유용한 경우
- 계산 비용이 큰 속성이나 함수 결과를 반복적으로 사용할 때.
- 객체의 상태가 불변이며, 속성 값이 변경되지 않을 때.
- 데이터베이스 쿼리, 파일 읽기와 같은 I/O 작업 결과를 캐시할 때.
cached_property
는 결과가 불변하는 상황에서 성능을 크게 개선할 수 있는 좋은 방법입니다.
반응형
'언어 > Python' 카테고리의 다른 글
[ Python ] SQLAlchemy + PostgreSQL - 데이터 베이스 연동하기 (1) | 2024.10.09 |
---|---|
[ Python ] SQLAlchemy + SQLite - 데이터 베이스 연결하기 (0) | 2024.10.09 |
[ Python ] sleep() 딜레이(delay) 하기 (2) | 2024.10.01 |
[ Python ] -menv 가상 환경을 사용하는 이유 - 개념 (1) | 2024.09.30 |
[ Python ] numpy 설치하기 (0) | 2024.09.07 |