簡體   English   中英

調用函數,直到其中一個不返回 None

[英]Call functions until one of them does not return None

我想調用不同的 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()

有沒有更方便的方法來做到這一點?

def tryFunctions():
    for func in [apicall1, apicall2]:
        try:
            return func()
        except:
            pass

好吧,您只需執行兩個功能即可:

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)

(海象運算符:=需要 Python 3.8。)

你可以這樣做。 (注意這里的tryFunctions function 是實際答案,而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 call_chainer(*funcs):
    for f, args in funcs:
        result = f(*args)
        if result is not None:
            return result

使用此 function,您可以構造一個應按順序嘗試的元組列表(callable, [arg1, arg2, argN])

def tryFunctions():
    functions = [(func1, []), (func2, [])]
    return call_chainer(*functions)
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()
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()

我認為這是最好的可讀方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM