0

This question is similar to here, but I forgot one detail to it.
I want to combine different functions with non-None parameters with and. Suppose I have this function: def foo(a,b,c). For every non-None parameter, I want to call a different function and linked with and. But if all of the parameters are None, it must return True. **The functions will return boolean and are already defined with the respecting parameters. ** For example, let the functions associated with a is bar_1, b is bar_2 and c is bar_3. Then the result will be having 7 combinations like this:

if a is not None and b is not None and c is not None:
    return bar_1(a) and bar_2(b) and bar_3(c)
elif a is None and b is not None and c is not None:
    return bar_2(b) and bar_3(c)
elif a is not None and b is None and c is not None:
    return bar_1(a) and bar_3(c)
elif a is not None and b is not None and c is None:
    return bar_1(a) and bar_2(b)
elif a is None and b is None and c is not None:
    return bar_3(c)
elif a is None and b is not None and c is None:
    return bar_2(b)
elif a is not None and b is None and c is None:
    return bar_1(a)
else:
    return True

How do I do this without listing all of the possible combinations of parameters? For example, is it possible to do something like this? (+= symbolizes and)

func = ...

if a is not None:
    func += bar_1(a)
if b is not None:
    func += bar_2(b)
if c is not None:
    func += bar_3(c)
if all of them wrong:
    return True
else:
    do func

1 Answers1

0

You can link a list of functions with a list of values using the zip function, for instance:

def f1(x):
    return x

def f2(x):
    return x - 1

def f3(x):
    return x - 2

def foo(a, b, c):
    return all(f(x) for f, x in zip([f1, f2, f3], [a, b, c]) if x is not None)

For instance, you get:

>>> foo(None, None,None)
True
>>> foo(2, 1, 0)
False
>>> foo(1, 2, 3)
True
>>> foo(0, 0, 0)
False

Of course, you can also drop zip and use tuples instead:

def foo(a, b, c):
    return all(f(x) for f, x in [(f1, a), (f2, b), (f3, c)] if x is not None)
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103