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

Question

Asked By – Eyelash

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.

Now we will see solution for issue: What is the most pythonic way to check if multiple variables are not None?


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]):

This question is answered By – Daniel Roseman

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0