调用函数,直到其中一个不返回None

问题描述 投票:1回答:6

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

还有其他更方便的方法吗?

python
6个回答
2
投票

嗯,只需执行两个功能:

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。)


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

0
投票

您可以通过某种合理的方式将呼叫链接在一起。

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)

0
投票
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()

我认为这是最好的可读方法


0
投票

您可以这样做。 (请注意,这里的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
    

0
投票
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()
© www.soinside.com 2019 - 2024. All rights reserved.