Which is more correct for compaing to None?
Greg Ball
gball at cfa.harvard.edu
Sat May 12 21:42:25 EDT 2001
> Both of these seem to work. Which is more correct?
>
> if foo is None:
> print 'is'
>
> if foo == None:
> print '=='
I'm going to use 'foo is None' in future...
The context I use this in is default arguments:
def plot(seqy, seqy=None):
if seqx is None:
seqx = range(len(seqy))
# plot seqy vs. seqx
...
In the newest version of Numerical Python, 'a == None' raises an exception
if a is a Numpy array.
'is' should be completely safe since it just uses object identity (i.e.
it doesn't ask the object how to do the comparison). I believe python
guarantees there is a unique None object.
In principle the object identity check is faster, particularly if foo
happens to be an instance, since a lot less work gets done under the
covers. It might even be faster than a truth test, but more importantly a
truth test might not be the right behaviour in general, where foo == ''
is meaningful for example.
The standard library says
$ grep 'is None' /usr/lib/python2.2/*.py | wc -l
280
$ grep 'is not None' /usr/lib/python2.2/*.py | wc -l
107
$ grep '== None' /usr/lib/python2.2/*.py | wc -l
0
grep '!= None' /usr/lib/python2.2/*.py | wc -l
0
with the first example that comes up appearing in BaseHTTPServer.py.
--Greg Ball
More information about the Python-list
mailing list