본문 바로가기

언어/Python

[ Python ] cached_property - 값을 재사용 하기

반응형

cached_property는 속성의 결과를 캐싱하여, 속성이 여러 번 호출될 때마다 매번 계산하지 않고 처음 계산된 값을 재사용하도록 하는 유용한 데코레이터입니다. Python 3.8 이상에서는 functools 모듈의 cached_property를 사용할 수 있습니다. 그 이전 버전에서는 werkzeug 라이브러리에서 제공하는 cached_property를 사용할 수 있습니다.

기본 사용 방법 (functools.cached_property)

Python 3.8 이상에서 functoolscached_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를 구현할 수 있습니다:

  1. werkzeug 설치:
   pip install werkzeug
  1. 사용 예시:
   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는 결과가 불변하는 상황에서 성능을 크게 개선할 수 있는 좋은 방법입니다.

반응형