2016-10-26 19 views
1

私は、lru_cacheを持つキャッシュを持つpythonの関数を持っています。Pythonのすべてのlru_cacheをクリア

@lru_cache(maxsize=None) 
def my_function(): 
    ... 

私は個々にキャッシュをクリアすることができますが、 my_function.cache_clear()は、すべての機能のキャッシュを一度にクリアする方法はありますか? [メモリにロードされたすべての関数名を返す方法があると思っていたのかもしれません。

私はマシン上のメモリの90%が使用されている場合に、特にフォールバックの一部として実装しようとしています。あなたが本当にあなたもオリジナルのデコレータを置き換えるために猿のパッチを使用することができますしたい場合は

cached_functions = [] 

def clearable_lru_cache(*args, **kwargs): 
    def decorator(func): 
     func = lru_cache(*args, **kwargs)(func) 
     cached_functions.append(func) 
     return func 

    return decorator 

def clear_all_cached_functions(): 
    for func in cached_functions: 
     func.cache_clear() 

+0

はい、装飾された機能は、現在の方法 'my_function.cache_clearを有します()'。 'my_function.cache_info()'で統計情報を取得することもできます。 ['lru_cache'](https://docs.python.org/3.5/library/functools.html?highlight=lru#functools.lru_cache)を参照してください。 – AChampion

+0

@AChampion - 確かに、それらの両方を認識していますが、質問はむしろですこれらのメソッドをすべての装飾された関数に適用する方法があります(つまり、lru_cacheをすべてクリアします)。 – kyrenia

+0

いいえ、すべての装飾されたファンクションキャッシュを消去する簡単な方法はありません。それらはすべて独立しています。それらのすべての関数のレジストリを作成し、それらを繰り返してクリアすることができます。 – AChampion

答えて

1

はまた、キャッシュされた機能の注意を要する修正デコレータを作成することができます。

試験:

@clearable_lru_cache() 
def foo(x): 
    print('foo', x) 

@clearable_lru_cache() 
def bar(x): 
    print('bar', x) 

for i in [1, 2]: 
    for j in [1, 2]: 
     print('Calling functions') 
     for k in [1, 2, 3]: 
      for f in [foo, bar]: 
       f(k) 
     print('Functions called - if you saw nothing they were cached') 
    print('Clearing cache') 
    clear_all_cached_functions() 

出力:

Calling functions 
foo 1 
bar 1 
foo 2 
bar 2 
foo 3 
bar 3 
Functions called - if you saw nothing they were cached 
Calling functions 
Functions called - if you saw nothing they were cached 
Clearing cache 
Calling functions 
foo 1 
bar 1 
foo 2 
bar 2 
foo 3 
bar 3 
Functions called - if you saw nothing they were cached 
Calling functions 
Functions called - if you saw nothing they were cached 
Clearing cache 
関連する問題