我正在尝试编写一个装饰器,以在使用函数之前检查特定的软件包是否可用。
在下面的示例中,numpy
不应引发错误,但non_existent_test_package
应通知用户他们需要安装软件包才能使用此功能。这样做的目的是减少依赖性。
import numpy as np
import importlib
def check_available_packages(packages):
if isinstance(packages,str):
packages = [packages]
packages = np.asarray(sorted(set(packages)))
def wrapper(func):
installed = list()
for package in packages:
try:
globals()[package] = importlib.import_module(package)
installed.append(True)
except ImportError:
installed.append(False)
installed = np.asarray(installed)
assert np.all(installed), "Please install the following packages to use this functionality:\n{}".format(", ".join(map(lambda x: "'{}'".format(x), packages[~installed])))
return func
return wrapper
@check_available_packages(["numpy"])
def f():
print("This worked")
@check_available_packages(["numpy", "non_existent_test_package"])
def f():
print("This shouldn't work")
# ---------------------------------------------------------------------------
# AssertionError Traceback (most recent call last)
# <ipython-input-222-5e8224fb30bd> in <module>
# 23 print("This worked")
# 24
# ---> 25 @check_available_packages(["numpy", "non_existent_test_package"])
# 26 def f():
# 27 print("This shouldn't work")
# <ipython-input-222-5e8224fb30bd> in wrapper(func)
# 15 installed.append(False)
# 16 installed = np.asarray(installed)
# ---> 17 assert np.all(installed), "Please install the following packages to use this functionality:\n{}".format(", ".join(map(lambda x: "'{}'".format(x), packages[~installed])))
# 18 return func
# 19 return wrapper
# AssertionError: Please install the following packages to use this functionality:
# 'non_existent_test_package'
现在装饰器似乎正在检查程序包是否在运行时存在,而不是实际调用函数时。如何调整此代码?
我正在尝试编写一个装饰器,以在使用函数之前检查特定的软件包是否可用。在下面的示例中,numpy不应引发错误,但non_existent_test_package应该......>
这将起作用
import numpy as np
import importlib
def check_available_packages(packages):
if isinstance(packages, str):
packages = [packages]
packages = np.asarray(sorted(set(packages)))
def decorator(func):
def wrapper():
installed = list()
for package in packages:
try:
globals()[package] = importlib.import_module(package)
installed.append(True)
except ImportError:
installed.append(False)
installed = np.asarray(installed)
assert np.all(installed), "Please install the following packages to use this functionality:\n{}".format(
", ".join(packages[~installed]))
func()
return wrapper
return decorator
@check_available_packages(["numpy"])
def foo():
print("This worked")
@check_available_packages(["numpy", "non_existent_test_package"])
def bar():
print("This shouldn't work")
foo()
bar()