``if t'' vs ``if t is not None''

Fredrik Lundh fredrik at pythonware.com
Thu Apr 22 08:13:39 EDT 1999


<jno at glasnet.ru> wrote:
> i faced a VERY strange behaviour of if-test operation!
> 
>    ``if t'' != ``if t is not None''
> where ``t'' is None or a class instance
> 
> i was writing a threader for a news reader.
> and found occasional hangs of a routine which builds the sequence of message
> numbers for "read next" operation.
> digging deeper brought me strange results: replacing ``if t'' with
> ``if t is not None'' speeded up the things dramatically!

"if t" evaluates "t" by calling it's __nonzero__ or __len__ methods
(see http://www.python.org/doc/ref/customization.html for
details).

"if t is not None" compares t's object identity (a pointer) with
the object identity for None (another pointer).

in other words, using "is" tests are always faster.  how much
faster depends on how much work you do in your __len__
(or __nonzero__) method...

</F>





More information about the Python-list mailing list