如何在python中使用相同的包装器包装多个函数



我是Python的新手,我还没有找到一个明确的方法。

我有几个函数(可能有数百个),我想在相同的代码中反复包装。

try:
OneOfTheOneHundredFunctions()
except MY_ERROR as error:
print('Error: I caught an error')

我必须为每个OneOfTheOneHundredFunctions()指定包装器吗?在c++中,我会用macro来做,在python中有类似的东西吗?

函数和异常是Python中的第一类成员,因此您可以简单地将它们传递给执行try/except块的另一个函数:

def try_to_run(function, error_to_catch, *args, **kwargs):
try:
return function(*args, **kwargs)
except error_to_catch:
print('Error: I caught an error')
def OneOfTheOneHundredFunctions():
pass
MY_ERROR = ValueError
result = try_to_run(
function=OneOfTheOneHundredFunctions, 
error_to_catch=MY_ERROR,
)

请注意,传递给try_to_run的任何附加参数/关键字参数都传递给您正在围绕try/except(这就是*args**kwargs的作用)的实际函数。

可以根据函数名引用它们,这样就可以在某个可迭代对象

中收集它们。
for index, fn in enumerate((  
function1,
function2,
function3,
)):
try:
fn()
except Exception as ex:
print(f"ERROR: function {index} raised {repr(ex)}")

enumerate在这里只是方便地在元组中获取函数的索引,但您可以将名称放入任何可迭代对象中,例如dict,并命名函数(带有一些注释?)

functions_dict = {"check A": fn1, "check B": fn2, ...}
for comment, function in functions_dict.items():
...

如果你在单独的文件中有函数,或者我认为你可能会分开它。然后,您可以使用此从该模块/文件中获取函数列表:
如何列出Python模块中的所有函数?另一个答案相同,但我认为是一些描述。

from inspect import getmembers, isfunction
from my_project import my_module
list_of_functions = getmembers(my_module, isfunction)

现在你可以遵循OPs的想法了。

喜欢@nanotek说:

def catch_error(my_function):
try:
my_function()
except MY_ERROR as error:
print('Error: I caught an error')
for function in list_of_functions:
catch_error(function)

实际上可以使用包装器创建一个函数,并传入指向所需的其他函数的指针。在包装器内部,您将调用指向。

的函数。
def catch_error(my_function):
try:
my_function()
except MY_ERROR as error:
print('Error: I caught an error')
list_of_functions = [OneOfTheHundredFunctions, TwoOfTheHundredFunctions, ...]
for function in list_of_functions:
catch_error(function)

# Calling functions out of order
catch_error(TwoOfTheHundredFunctions)
# Some more logic
catch_error(OneOfTheHundredFunctions)

最新更新