Python: comparing with None


Python's documentation states that one has to use is operator co compare a variable with 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's because len(q) == 0!
The conclusion:
1
2
if q is None:
    doSomething()

Leave a comment

Introduce yourself:
Comment: BB-codes
Captcha:
captcha