[FRPythoneers] Python documentation and default expression

Matt Gushee mgushee at havenrock.com
Fri Mar 15 18:50:06 MST 2002


On Fri, Mar 15, 2002 at 06:16:36PM -0700, Jeffery D. Collins wrote:

> > I've almost always used "if foo != None:". Is there a reason not to
> > write it as such?

> No. 

There may be in some applications.

 The "is" compares object identities and the "==" ("!=") compares object
> values.
> Since None is a singleton and comparisons are always done wrt to its
> identity,
> the results will be identical.

That's all true, but there are performance differences that may be 
significant if you are iterating over a large set of objects. I've done
an informal benchmark. Since the actual comparison is probably the least
expensive part of the test function, I'd say the ~25% difference I'm 
seeing is quite significant. This will undoubtedly vary according to
platform, Python implementation, etc. I ran this on Linux (kernel 2.2.19,
glibc 2.1) with cPython 2.1. I also did a similar test comparing two
integers, which found no significant differences between 'is' and '=='.
Presumably '==' is more expensive on class instances because it involves
inspecting the object, whereas an 'is' comparison just uses the object
ID -- or something like that.

>>> import time, whrandom
>>> class Dummy:
...     pass
...
>>> def getObj():
...     num = whrandom.randint(1,2)
...     if num & 2:
...             return Dummy()
...     else:
...             return None
...
>>> def test_is(iterations=10000):
...     start = time.time()
...     for i in range(iterations):
...             getObj() is None
...     print `time.time() - start`
... 
>>> def test_eq(iterations=10000):
...     start = time.time()
...     for i in range(iterations):
...             getObj() == None
...     print `time.time() - start`
... 
>>> test_is()
15.393565058708191
>>> test_eq()
20.407405972480774
>>> test_is()
15.6302330493927
>>> test_eq()
19.003860950469971
>>> test_is()
15.556992053985596
>>> test_eq()
20.201207995414734
>>> 
-- 
Matt Gushee
Englewood, Colorado, USA
mgushee at havenrock.com
http://www.havenrock.com/



More information about the FRPythoneers mailing list