Skip to content
Advertisement

What is the most pythonic way to check if multiple variables are not None?

If I have a construct like this:

def foo():
    a=None
    b=None
    c=None

    #...loop over a config file or command line options...

    if a is not None and b is not None and c is not None:
        doSomething(a,b,c)
    else:
        print "A config parameter is missing..."

What is the preferred syntax in python to check if all variables are set to useful values? Is it as I have written, or another better way?

This is different from this question: not None test in Python … I am looking for the preferred method for checking if many conditions are not None. The option I have typed seems very long and non-pythonic.

Advertisement

Answer

There’s nothing wrong with the way you’re doing it.

If you have a lot of variables, you could put them in a list and use all:

if all(v is not None for v in [A, B, C, D, E]):
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement