본문 바로가기

파이썬

functools.lru_cache (functools.cache)

@functools.lru_cache(user_function)
@functools.lru_cache(maxsize=128, typed=False)

최근 maxsize 개의 호출까지 기억하는 callable 함수의 decorator이다.

간단한 예제인 피보나치를 통해 동작방식을 살펴볼 수 있다.

def fibo(n):
    print("now : %s"%n)
    if n < 2:
        return n
    return fibo(n-1) + fibo(n-2)

print(fibo(5))
now : 5
now : 4
now : 3
now : 2
now : 1
now : 0
now : 1
now : 2
now : 1
now : 0
now : 3
now : 2
now : 1
now : 0
now : 1
5

 

아래는 decorator를 적용한 결과이다.

@functools.lru_cache
def fibo(n):
    print("now : %s"%n)
    if n < 2:
        return n
    return fibo(n-1) + fibo(n-2) 

print(fibo(5))
now : 5
now : 4
now : 3
now : 2
now : 1
now : 0
5

 

함수의 parameter가 여러개여도 캐싱이 가능하다.

3.3 버전에 추가된 typed를 true로 하면 parameter의 type에 따라서도 다르게 캐싱된다. 기본값은 False 다.

import functools

@functools.lru_cache
def get_something(a,b):
    print("{} {}".format(a,b))
    return a,b

@functools.lru_cache(typed = True)
def get_something_type(a,b):
    print("{} {}".format(a,b))
    return a,b

print("get something")
get_something(3.0, 'a')
get_something(3,   'a')

print("get something type")
get_something_type(3.0, 'a')
get_something_type(3,   'a')
get something
3.0 a
get something type
3.0 a
3 a

 

캐시를 지우고 싶다면 cache_clear() 를 사용하면 된다.

@functools.lru_cache
def get_something(a,b):
    return a,b
    
get_something.cache_clear()

 

3.9 버전에서는 무제한 함수 캐시인 @functools.cache 를 제공한다.

'파이썬' 카테고리의 다른 글

For 문 에서의 List Comprehension  (0) 2023.09.26
list, str reverse  (0) 2021.08.04
Python으로 2D Array rotaton 하기  (0) 2021.07.28
Virtualenv 실행시 오류  (0) 2021.02.07