20
Variable = None

Is there any difference between these three in a specific scenario ? if there is no difference which one is more suitable to use?

if Variable:
 print "Hello world"

and

if Variable is not None:
 print "Hello world"

and

if Variable != None:
 print "Hello world"

are same in case of None Variable ?

NIlesh Sharma
  • 5,445
  • 6
  • 36
  • 53
  • Maybe he mixed up `if x is None` and `if x == None` – jamylak Mar 27 '13 at 05:29
  • yeah, right. Thanks for reminding – NIlesh Sharma Mar 27 '13 at 05:29
  • This should be closed, it is either not a real question or a duplicate. http://stackoverflow.com/questions/3257919/is-none-vs-none http://stackoverflow.com/questions/7816363/if-a-vs-if-a-is-not-none – jamylak Mar 27 '13 at 05:34
  • Well, both of those (which seem to be dups of each other) just cover the `if a` vs. `if a is not None`; neither covers the difference between both of those and `if a != None` (which would be a dup of [Is there a difference between `==` and `is` in python?](http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python/134659). So, I'm not sure how to close it… – abarnert Mar 27 '13 at 05:40
  • 4
    This question is real enough and it seems sufficiently distinct to me to warrant keeping it open. – Raymond Hettinger Mar 27 '13 at 06:26

4 Answers4

14

Is there any difference between these three in a specific scenario ?

The first asks whether the variable is anything falsy. This test will fail for all kinds of things besides NoneFalse, 0, any empty sequence, etc.

The second asks whether it's the magic singleton constant None. This will fail only for None itself.

The third asks whether it's anything that considers itself equal to None. This will fail for, say, Holder(None), where Holder is a wrapper class whose instances compare equal to whatever they're holding. Or, to give a less realistic but shorter to code exmaple:

class Stupid(object):
    def __ne__(self, other):
        return False
Variable = Stupid()

The last one is rarely useful; in fact, if you ever think you might need to check == None or != None, and you haven't specifically been creating transparent-wrapper classes or anything like that, you probably actually wanted is None or is not None. But the other two are both very useful and common.

if there is no difference which one is more suitable to use?

Well, there is a difference, and which one is more suitable depends on the specific use.

At the end of the question, it seems like you might be asking whether there's any difference in the specific case where Variable is definitely None. In that case, of course there is no functional difference between the three.* All of them are guaranteed to be false, and therefore do nothing. Which means there's also no difference between any of the three and writing no code at all. Which is a lot simpler, more readable, and faster.

* There is a performance difference—the first one doesn't have to LOAD_CONST the None, or call a comparison operator. And, even if you've somehow managed to rebind None or change the value of the None constant (maybe by stomping all over the heap with ctypes?), the first one is more likely to still work. But neither of these is ever going to matter—and, if they do, again, no code at all will be even faster and more reliable.

abarnert
  • 354,177
  • 51
  • 601
  • 671
8

not x will be true if x is None, False, [], {}, etc.

x is not None will always be True, unless a variable is actually None.

Edit:

This is of practical importance, whenever you want to check if a variable is actually set to a proper value. Otherwise you can run into problems. For example, if you want to evaluate a list of items and do:

if not x:

to check if a list was provided, then the condition will trigger on an empty list, which may still be a valid input. So in that case, you'd like to check with

if x is not None:

to allow empty lists as valid inputs, but still check the case that no list at all was provided.

The None value as such is comparable to a null or nil value in certain languages. It's a placeholder for the lack of a value in a defined variable (if it is undefined, it will throw a NameError). That's why the None value is used as a default value in some cases:

>>> def foo():
...     pass
...
>>> x = foo()
>>> x is None
True

It's also frequently used as a default value for optional variables:

>>> def foo(bar=None):
...     if bar is None:
...         print('No argument passed.')
...     else:
...         print('Variable bar: %s' % str(bar))
...
>>> foo(0)
Variable bar: 0
>>> foo()
No argument passed.

This way, 0 is still a valid value, that would evaluate to False if checked with if not bar:.

Stjepan Bakrac
  • 1,047
  • 11
  • 18
5

The official PEP 8 recommendation is to test for None with an identity check:

if Variable is not None:
    print "Hello world"

The equality/inequality test would also work but would be slower and non-idiomatic:

if Variable != None:
    print "Hello world"

Testing the boolean value of the Variable produces a different result. The following test would print "hello world" if the variable were an empty container or a number equal to zero:

# Hello world won't print for any of these values:
for Variable in (), '', u'', {}, [], 0, 0.0, 0j, None:
    if Variable:
        print "Hello world"
gerardw
  • 5,822
  • 46
  • 39
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
2

They are different. not checks if bool(var) evaluates to False.

eg.

>>> not ''
True
>>> not 'abc'
False
>>> not 0
True

if x is None checks if x is None itself.

jamylak
  • 128,818
  • 30
  • 231
  • 230