Which is more correct for compaing to None?
gry at ll.mit.edu
Sat May 26 13:54:49 EDT 2001
Hmm, am I missing something? I find it very convenient and *clear* to
print 'yep, foo'
if not foo:
print 'nope, not foo'
This lets me benefit from whatever clever member function a third party
might use to implement this, and also works for simple types too. I
suppose it misses
the distinction between 0 and None for a numeric type, but I think it
better to not
rely on that distinction anyway, for this very reason. I guess this
seems the clear,
simple pythonic way to do things. I would like to hear why people
Just to argue metrics, in the python(2.0) library:
egrep 'if [A-Za-z_][A-Za-z_0-9]* *:' *.py|wc -l
[I don't really think most is best, just being argumentative...]
Greg Ball wrote:
> > 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
> $ grep 'is not None' /usr/lib/python2.2/*.py | wc -l
> $ grep '== None' /usr/lib/python2.2/*.py | wc -l
> grep '!= None' /usr/lib/python2.2/*.py | wc -l
> with the first example that comes up appearing in BaseHTTPServer.py.
> --Greg Ball
More information about the Python-list