我想调用不同的Rest-API。如果通话不起作用,我想尝试下一个。我当前的解决方案:
def func1():
try:
return apicall1()
except:
return None
def func2():
try:
return apicall2()
except:
return None
def tryFunctions():
df = func1()
if df is None:
df = func2()
return df
df = tryFunctions()
还有其他更方便的方法吗?
嗯,只需执行两个功能:
df = df if (df := func1()) is not None else func2()
[具有两个以上的功能,设置一个可迭代的功能:
funcs = [func1, func2, func3, ...]
df = next((df for f in funcs if (df := f()) is not None), None)
((Walrus运算符:=
需要Python 3.8。)
def tryFunctions():
for func in [apicall1, apicall2]:
try:
return func()
except:
pass
您可以通过某种合理的方式将呼叫链接在一起。
def call_chainer(*funcs):
for f, args in funcs:
result = f(*args)
if result is not None:
return result
使用此功能,您可以构建应按顺序尝试的元组(callable, [arg1, arg2, argN])
的列表。
def tryFunctions():
functions = [(func1, []), (func2, [])]
return call_chainer(*functions)
while True:
api = True
try:
api = apicall1()
except Exception:
continue
try:
api = apicall2()
except Exception:
continue
try:
api = apicall3()
except Exception:
continue
if api:
print("ERROR")
exit()
我认为这是最好的可读方法
您可以这样做。 (请注意,这里的tryFunctions
函数是实际的答案,apicall*
函数和最终的print
语句是说明该功能的测试代码。)]
def apicall1(): raise RuntimeError def apicall2(): return "it was 2" def tryFunctions(): for apicall in apicall1, apicall2: try: return apicall() except: pass return "none of them worked" print(tryFunctions())
给予:
it was 2
def func1():
try:
return apicall1()
except:
return func2()
def func2():
try:
return apicall2()
except:
return None
def tryFunctions():
All_func = [func1(),func2(),func3(),...,funcn()]
for funct in All_func:
if funct is None:
continue
else:
return funct
df = tryFunctions()