简体   繁体   English

如何尝试不同的功能,并返回在python中成功的第一个输出?

[英]How to try different function, and return first output that succeds in python?

I have a couple of different functions, that each outputs a json string if successful. 我有几个不同的函数,如果成功,每个函数都会输出一个json字符串。 I cannot know beforehand whether they will fail or not so I want have to try them all in the order specified below. 我无法事先知道它们是否会失败,因此我想按以下指定的顺序全部尝试它们。 How can I do this? 我怎样才能做到这一点?

I have tried things like: 我已经尝试过类似的事情:

import func1
import func2
import func3

def compi(url):
    try:
        return func1(url)
    except:
        return func2(url)
    else:
        return func3(url)

I am certain that func3 will not fail. 我确信func3不会失败。

def compi(url):
    functions = [func1, func2, func3]
    for func in functions:
        try:
            return func(url)
        except:
            pass
    #oops, none of them succeeded.
    raise Exception("All functions failed to return a value.")

Python functions are first-class objects, so instead of going through them manually, you can just make a list of them and loop through it, like so: Python函数是一流的对象,因此您无需列出它们并手动遍历它们,而无需手动进行操作,如下所示:

tested_funcs = [f1, f2, f3]
for f in tested_funcs:
    result = f(someinput)
    if result: break
return result

Wrap the inner block in a try/catch if it throws an error upon failing. 如果内部块在失败时引发错误,则将其包装在try / catch中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM