Python: comparing to None

01 AUGUST 2011
PROGRAMMING PYTHON

Python's documentation states that one has to use the is operator to compare a variable to None. What happens when you avoid that advice?

Consider a class:

1
2
3
4
5
6
class Queue(object):
    def __init__(self):
        self._len = 0

    def __len__(self):
        return self._len

Next, the usage of the class is:

1
2
3
4
5
q = Queue()

# at this point, you want to check if q is None
if not q:
   doSomething()

The confusing thing is that doSomething() is actually called! And that is because len(q) == 0!

Instead, use the is None comparison:

1
2
if q is None:
    doSomething()