bwalsh434 bwalsh434 - 1 year ago 112
Python Question

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:

function2(var) or function3(var) or function4(var)

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

Answer Source

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:
            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)
    # call to a failed
    # call to b failed
    # OK

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

Runnable snippet:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download