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.
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).
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.
Use the == operator to test if two variables are equal.
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):
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.
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]):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With