我使用joblib.Memory
模块在几个模块中缓存某些功能。缓存分别在模块和类中初始化。
Module1:
memory = Memory(location='/cache/')
@memory.cache
def heavy_function(...)
.....
Module2:
memory = Memory(location='/cache/')
@memory.cache
def heavy_function2(...)
.....
Module3:
import Module1
import Module2
def heavy_function3(...)
Module1.heavy_function1(...)
Module1.heavy_function1(...)
.....
现在我有一个单元测试脚本,我想在单元测试期间全局禁用高速缓存的使用,以确保正确地计算了所有内容。
是否可以通过以下方式为每个模块手动禁用它?
Module1.memory.cachedir=None
还是不删除cachedir?
我当前的解决方案只是手动修补每个内存调用
unittest1:
from joblib import Memory
import Module1
Module1.memory = Memory(location=None)
...
unittest.run()
unittest3:
from joblib import Memory
import Module1 # need to import module 1 just to disable its memory
import Module2 # need to import module 2 just to disable its memory
import Modul3
Module1.memory = Memory(location=None)
Module2.memory = Memory(location=None)
...
unittest.run()
我创建的模块越多,所需的内存修补就越多。我认为可能会有更好的解决方案。我在下面提出了一种解决方法。
答案 0 :(得分:1)
要全局禁用joblib.memory
缓存,我将看一下调用register_store_backend
并用不执行任何操作的DummyStoreBackend
覆盖默认的“本地” FileSystemStoreBackend
。
类似于以下内容,请注意DummyStoreBackend
是从Memory
的单元测试中复制的,我尚未测试它是否按预期工作
from joblib.memory import register_store_backend
from joblib._store_backends import StoreBackendBase
class DummyStoreBackend(StoreBackendBase):
"""A dummy store backend that does nothing."""
def _open_item(self, *args, **kwargs):
"""Open an item on store."""
"Does nothing"
def _item_exists(self, location):
"""Check if an item location exists."""
"Does nothing"
def _move_item(self, src, dst):
"""Move an item from src to dst in store."""
"Does nothing"
def create_location(self, location):
"""Create location on store."""
"Does nothing"
def exists(self, obj):
"""Check if an object exists in the store"""
return False
def clear_location(self, obj):
"""Clear object on store"""
"Does nothing"
def get_items(self):
"""Returns the whole list of items available in cache."""
return []
def configure(self, location, *args, **kwargs):
"""Configure the store"""
"Does nothing"
register_store_backend("local", DummyStoreBackend)
答案 1 :(得分:0)
一种解决方法是在运行测试时设置标志或环境变量。然后在初始化内存之前检查以下标志:
Module1
import os
memflag = os.environ.get('UNITTESTING', False)
memory = Memory(location= None if memflag else '/cache/')
@memory.cache
def heavy_function(...)
.....
unittest1
os.environ["UNITTESTING"] = '1'
import Module1
.....
unittest.run()
del os.environ["UNITTESTING"]