0

I want to combine 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 function, for example bar and linked with and. But if all of the parameters are None, So, in the example, the result will be having 6 combinations like this:

if a is not None and b is not None and c is not None:
    return bar(a) and bar(b) and bar(c)
elif a is None and b is not None and c is not None:
    return bar(b) and bar(c)
elif a is not None and b is None and c is not None:
    return bar(a) and bar(c)
elif a is not None and b is not None and c is None:
    return bar(a) and bar(b)
elif a is None and b is None and c is not None:
    return bar(c)
elif a is None and b is not None and c is None:
    return bar(b)
elif a is not None and b is None and c is None:
    return bar(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(a)
if b is not None:
    func += bar(b)
if c is not None:
    func += bar(c)
if all of them wrong:
    return True
else:
    do func

2 Answers2

2

If you want the result of anding these arguments, you can just use all() and filter out the Nones:

def bar(n):
    return n

def foo(a,b,c):
    return all(bar(arg) for arg in [a, b, c] if arg is not None)

foo(None, True, True)
# True

foo(False, True, None)
# False
Mark
  • 90,562
  • 7
  • 108
  • 148
0

You can use *args to pack variable parameters and iterate through them. I assume that bar returns a boolean, allowing us to use &=.

def foo(*args):
    result = True
    for param in args:
        if param is not None:
            result &= bar(param)
    return result
TrebledJ
  • 8,713
  • 7
  • 26
  • 48