[英]How to wrap many functions with same wrapper in python
I am new in Python and I did not find a clear method yet.我是 Python 新手,还没有找到明确的方法。
I have several functions (possibly hundreds) that I want to wrap in the same code over and over.我有几个函数(可能有数百个),我想一遍又一遍地包装在相同的代码中。
try:
OneOfTheOneHundredFunctions()
except MY_ERROR as error:
print('Error: I caught an error')
Do I have to specify the wrapper for each of the OneOfTheOneHundredFunctions()
?我是否必须为每个
OneOfTheOneHundredFunctions()
指定包装器? In C++, I would do that with a macro
, is there something similar in python?在 C++ 中,我会用
macro
来做到这一点,python 中是否有类似的东西?
You can reference functions by their name, so you can collect them in some iterable您可以通过它们的名称引用函数,因此您可以将它们收集在一些可迭代的
for index, fn in enumerate((
function1,
function2,
function3,
)):
try:
fn()
except Exception as ex:
print(f"ERROR: function {index} raised {repr(ex)}")
enumerate
is just convenient here to get the index of the function in a tuple, but you can put the names into any iterable, like a dict
and also name the functions (with some comment?) enumerate
在这里只是方便获取元组中函数的索引,但是您可以将名称放入任何可迭代对象中,例如dict
并命名函数(带一些注释?)
functions_dict = {"check A": fn1, "check B": fn2, ...}
for comment, function in functions_dict.items():
...
You could essentially create a function with the wrapper, and pass in a pointer to the other functions you want.您基本上可以使用包装器创建一个函数,并传入一个指向您想要的其他函数的指针。 Inside the wrapper you would call the function that's pointed to.
在包装器内,您将调用指向的函数。
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)
Functions and Exceptions are first-class members in Python, so you can simply pass them into another function that does the try/except block:函数和异常是 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,
)
Note that any additional arguments/keyword arguments passed to try_to_run
are passed in to the actual function you're wrapping around the try/except (that's what the *args
and **kwargs
are for).请注意,传递给
try_to_run
任何其他参数/关键字参数都将传递给您包装 try/except 的实际函数(这就是*args
和**kwargs
的用途)。
If you have functions in separate file, or I think you may separate it.如果您在单独的文件中有函数,或者我认为您可以将其分开。 Then you can use this to get list of function from that module/file:
然后您可以使用它从该模块/文件中获取函数列表:
How to list all functions in a Python module?如何列出 Python 模块中的所有函数? another answer same but I think some description.
另一个答案相同,但我认为有一些描述。
from inspect import getmembers, isfunction from my_project import my_module list_of_functions = getmembers(my_module, isfunction)
And now you can follow OPs ideas.现在您可以遵循 OP 的想法。
Like @nanotek said :就像@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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.