'Why is "if not someobj:" better than "if someobj == None:" in Python?

I've seen several examples of code like this:

if not someobj:
    #do something

But I'm wondering why not doing:

if someobj == None:
    #do something

Is there any difference? Does one have an advantage over the other?



Solution 1:[1]

These are actually both poor practices. Once upon a time, it was considered OK to casually treat None and False as similar. However, since Python 2.2 this is not the best policy.

First, when you do an if x or if not x kind of test, Python has to implicitly convert x to boolean. The rules for the bool function describe a raft of things which are False; everything else is True. If the value of x wasn't properly boolean to begin with, this implicit conversion isn't really the clearest way to say things.

Before Python 2.2, there was no bool function, so it was even less clear.

Second, you shouldn't really test with == None. You should use is None and is not None.

See PEP 8, Style Guide for Python Code.

- Comparisons to singletons like None should always be done with
  'is' or 'is not', never the equality operators.

  Also, beware of writing "if x" when you really mean "if x is not None"
  -- e.g. when testing whether a variable or argument that defaults to
  None was set to some other value.  The other value might have a type
  (such as a container) that could be false in a boolean context!

How many singletons are there? Five: None, True, False, NotImplemented and Ellipsis. Since you're really unlikely to use NotImplemented or Ellipsis, and you would never say if x is True (because simply if x is a lot clearer), you'll only ever test None.

Solution 2:[2]

Because None is not the only thing that is considered false.

if not False:
    print "False is false."
if not 0:
    print "0 is false."
if not []:
    print "An empty list is false."
if not ():
    print "An empty tuple is false."
if not {}:
    print "An empty dict is false."
if not "":
    print "An empty string is false."

False, 0, (), [], {} and "" are all different from None, so your two code snippets are not equivalent.

Moreover, consider the following:

>>> False == 0
True
>>> False == ()
False

if object: is not an equality check. 0, (), [], None, {}, etc. are all different from each other, but they all evaluate to False.

This is the "magic" behind short circuiting expressions like:

foo = bar and spam or eggs

which is shorthand for:

if bar:
    foo = spam
else:
    foo = eggs

although you really should write:

foo = spam if bar else egg

Solution 3:[3]

PEP 8 -- Style Guide for Python Code recommends to use is or is not if you are testing for None-ness

- Comparisons to singletons like None should always be done with
  'is' or 'is not', never the equality operators.

On the other hand if you are testing for more than None-ness, you should use the boolean operator.

Solution 4:[4]

If you ask

if not spam:
    print "Sorry. No SPAM."

the __nonzero__ method of spam gets called. From the Python manual:

__nonzero__(self) Called to implement truth value testing, and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, __len__() is called, if it is defined (see below). If a class defines neither __len__() nor __nonzero__(), all its instances are considered true.

If you ask

if spam == None:
    print "Sorry. No SPAM here either."

the __eq__ method of spam gets called with the argument None.

For more information of the customization possibilities have a look at the Python documenation at https://docs.python.org/reference/datamodel.html#basic-customization

Solution 5:[5]

These two comparisons serve different purposes. The former checks for boolean value of something, the second checks for identity with None value.

Solution 6:[6]

For one the first example is shorter and looks nicer. As per the other posts what you choose also depends on what you really want to do with the comparison.

Solution 7:[7]

The answer is "it depends".

I use the first example if I consider 0, "", [] and False (list not exhaustive) to be equivalent to None in this context.

Solution 8:[8]

Personally, I chose a consistent approach across languages: I do if (var) (or equivalent) only if var is declared as boolean (or defined as such, in C we don't have a specific type). I even prefix these variables with a b (so it would be bVar actually) to be sure I won't accidentally use another type here.
I don't really like implicit casting to boolean, even less when there are numerous, complex rules.

Of course, people will disagree. Some go farther, I see if (bVar == true) in the Java code at my work (too redundant for my taste!), others love too much compact syntax, going while (line = getNextLine()) (too ambiguous for me).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 S.Lott
Solution 2
Solution 3 Y.D.X.
Solution 4 twasbrillig
Solution 5 zgoda
Solution 6 rslite
Solution 7 Matthias Kestenholz
Solution 8 PhiLho