[英]How to wrap many functions with same wrapper in python
我是 Python 新手,還沒有找到明確的方法。
我有幾個函數(可能有數百個),我想一遍又一遍地包裝在相同的代碼中。
try:
OneOfTheOneHundredFunctions()
except MY_ERROR as error:
print('Error: I caught an error')
我是否必須為每個OneOfTheOneHundredFunctions()
指定包裝器? 在 C++ 中,我會用macro
來做到這一點,python 中是否有類似的東西?
您可以通過它們的名稱引用函數,因此您可以將它們收集在一些可迭代的
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():
...
您基本上可以使用包裝器創建一個函數,並傳入一個指向您想要的其他函數的指針。 在包裝器內,您將調用指向的函數。
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)
函數和異常是 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
的用途)。
如果您在單獨的文件中有函數,或者我認為您可以將其分開。 然后您可以使用它從該模塊/文件中獲取函數列表:
如何列出 Python 模塊中的所有函數? 另一個答案相同,但我認為有一些描述。
from inspect import getmembers, isfunction from my_project import my_module list_of_functions = getmembers(my_module, isfunction)
現在您可以遵循 OP 的想法。
就像@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.