When to use None

Laurence Tratt tratt at dcs.kcl.ac.uk
Tue Feb 1 17:00:06 EST 2000


stevie_deja at my-deja.com wrote:

> Would anyone explain to me where there is a difference between the
> following two calls:
> 
> if some_var == None :  print 'var is none'
> 
> if some_var is None :  print 'var is none'
> 
> Can '== None' only be used in certain circumstances?

In this particular circumstance, both lines of code will always produce the
same result; however they achieve it in a different way. The first line says
"are the contents of some_var the same as the contents of None?" (None is a
genuine Python object); the second says "is some_var the same object as
None?" (ie similar to "if id(some_var) == id(None)").

The second version is faster, as it has a very easy job; the first version
can take an indeterminate amount of time depending on the __cmp__ method of
the some_var object.

So, conceptually, the second line is generally probably "better" becuase
you're emphasising the uniqueness of the None object... But I fully admit
that in practice I tend to forget that, and use == out of force of habit.


Laurie



More information about the Python-list mailing list