Reputation: 11
I have 5 user-defined functions f1
, f2
, f3
, f4
and f5
. Right now I am using that as:
try:
f1()
except:
pass
try:
f2()
except:
pass
try:
f3()
except:
pass
try:
f4()
except:
pass
try:
f5()
except:
pass
I want to know a simpler method to iterate over this list of functions while using try and except on each function call.
Upvotes: 1
Views: 1085
Reputation: 21
Use a python decorator:
def add_try_func(func):
def _try(*args, **kwargs):
try:
res = func(*args, **kwargs)
print('add try func')
## return res
except:
pass
return _try
@add_try_func
fun1()
@add_try_func
fun2()
@add_try_func
fun3()
Upvotes: 2
Reputation: 567
Functions are variables like any other and you can iterate over a list of them.
for func in [f1, f2, f3, f4, f5]:
try:
func()
except:
pass
Upvotes: 1