如果確定函數失敗的成功與否,是否引發異常,您可以編寫一個助手方法,它會嘗試調用函數列表,直到成功函數返回。
#!/usr/bin/env python
# coding: utf-8
import sys
def callany(*funs):
"""
Returns the return value of the first successfully called function
otherwise raises an error.
"""
for fun in funs:
try:
return fun()
except Exception as err:
print('call to %s failed' % (fun.__name__), file=sys.stderr)
raise RuntimeError('none of the functions could be called')
if __name__ == '__main__':
def a(): raise NotImplementedError('a')
def b(): raise NotImplementedError('b')
# def c(): raise NotImplementedError('c')
c = lambda: "OK"
x = callany(a, b, c)
print(x)
# call to a failed
# call to b failed
# OK
上面的玩具實現可以通過添加對函數參數的支持來改進。
可運行的代碼片段:https://glot.io/snippets/ehqk3alcfv
如果功能指示返回一個布爾值的成功,你可以使用它們,就像在一個普通的布爾表達式。