简体   繁体   中英

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. 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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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