Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 857
Eyelash Avatar asked Feb 21 '17 07:02

Eyelash


People also ask

How do you know if a variable is not none?

Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).

What does not none mean in Python?

It's often used as the default value for optional parameters, as in: def sort(key=None): if key is not None: # do something with the argument else: # argument was omitted. If you only used if key: here, then an argument which evaluated to false would not be considered.

How do you check if variables are the same in Python?

Use the == operator to test if two variables are equal.

How do you check if something is equal to multiple values in Python?

if x == 1 or y == 1 or z == 1: x and y are otherwise evaluated on their own ( False if 0 , True otherwise). You can shorten that using a containment test against a tuple: if 1 in (x, y, z):


2 Answers

It can be done much simpler, really

if None not in (a, b, c, d):     pass 

UPDATE:

As slashCoder has correctly remarked, the code above implicitly does a == None, b == None, etc. This practice is frowned upon. The equality operator can be overloaded and not None can become equal to None. You may say that it never happens. Well it does not, until it does. So, to be on the safe side, if you want to check that none of the objects are None you may use this approach

if not [x for x in (a, b, c, d) if x is None]:     pass 

It is a bit slower and less expressive, but it is still rather fast and short.

like image 131
serge.v Avatar answered Sep 21 '22 17:09

serge.v


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]): 
like image 45
Daniel Roseman Avatar answered Sep 20 '22 17:09

Daniel Roseman