2024-10-03 11:21:26 发布
网友
我有一个可以使用两个模块的库;一个速度很快,但仅在Linux和macOS上可用,另一个速度较慢,但它是多平台的。我的解决方案是使库与两者兼容,并具有如下内容:
try: import fastmodule except ImportError: import slowmodule
现在,我想比较使用两个模块时库的计时。在安装了两个模块的环境中,是否有任何方法可以在不更改源代码的情况下屏蔽fastmodule(即在Jupyter笔记本中),从而使用slowmodule
fastmodule
slowmodule
这有点像黑客,但它是这样的: 您可以编写自己的导入程序并注册它(注意,这是特定于Python 3的,Python 2为此提供了另一个API):
import sut import functools import importlib import sys def use_slow(f): @functools.wraps(f) def wrapped(*args, **kwargs): ImportRaiser.use_slow = True if 'fastmodule' in sys.modules: del sys.modules['fastmodule'] # otherwise it will remain cached importlib.reload(sut) f(*args, **kwargs) return wrapped def use_fast(f): @functools.wraps(f) def wrapped(*args, **kwargs): ImportRaiser.use_slow = False importlib.reload(sut) f(*args, **kwargs) return wrapped class ImportRaiser: use_slow = False def find_spec(self, fullname, path, target=None): if fullname == 'fastmodule': if self.use_slow: raise ImportError() sys.meta_path.insert(0, ImportRaiser()) @use_fast def test_fast(): # test code @use_slow def test_slow(): # test code
这里,sut是您正在测试的模块,您必须重新加载它才能更改行为。我为可读性添加了decorators,但这可以通过一些函数或在测试设置中完成
sut
如果使用慢速版本,fastmodule将在导入时引发ImportError,而使用slowmodule。在“快速”的情况下,一切正常
ImportError
这有点像黑客,但它是这样的:
您可以编写自己的导入程序并注册它(注意,这是特定于Python 3的,Python 2为此提供了另一个API):
这里,
sut
是您正在测试的模块,您必须重新加载它才能更改行为。我为可读性添加了decorators,但这可以通过一些函数或在测试设置中完成如果使用慢速版本,
fastmodule
将在导入时引发ImportError
,而使用slowmodule
。在“快速”的情况下,一切正常相关问题 更多 >
编程相关推荐