简体   繁体   中英

Call function or function (python)

I have 4 functions. I want my code to perform the first one AND the second, third, or fourth. I also want at least one (any of them) no matter what unless they all fail. My initial implementation was:

try:
    function1(var)
except:
    pass
try:
    function2(var) or function3(var) or function4(var)
except:
    pass

If function2 doesn't work, it doesn't go to function3, how might this be coded to account for that?

In case the success of failure of a function is determined, whether it raises an exception or not, you could write a helper method, that would try to call a list of functions until a successful one returns.

#!/usr/bin/env python
# coding: utf-8

import sys

def callany(*funs):
    """
    Returns the return value of the first successfully called function
    otherwise raises an error.
    """
    for fun in funs:
        try:
            return fun()
        except Exception as err:
            print('call to %s failed' % (fun.__name__), file=sys.stderr)
    raise RuntimeError('none of the functions could be called')

if __name__ == '__main__':
    def a(): raise NotImplementedError('a')
    def b(): raise NotImplementedError('b')
    # def c(): raise NotImplementedError('c')
    c = lambda: "OK"

    x = callany(a, b, c)
    print(x)
    # call to a failed
    # call to b failed
    # OK

The toy implementation above could be improved by adding support for function arguments.

Runnable snippet: https://glot.io/snippets/ehqk3alcfv

If the functions indicate success by returning a boolean value, you can use them just as in an ordinary boolean expression.

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