Python: comparing to None
Posted on 01 August 2011 in Articles • 1 min read
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() |