Since a lot of people trip over this, let me repeat an important and useful
passage from PEP8,
the Python styleguide:
- 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!
In particular, you should avoid code like
ob = retrieveObjectSomehow(..., default=None)
if ob:
# you'll never get here if ob is an IContainer and empty
If you know that None is the fallback, then check for it
explicitly:
ob = retrieveObjectSomehow(..., default=None)
if ob is not None:
I don't know why people frequently trip over this, I blame tutorials that
draw a misleading picture of Python's polymorphism.