Difference between 'is' and '=='

Joel Hedlund joel.hedlund at gmail.com
Mon Mar 27 14:52:46 CEST 2006


> "is" is like id(obj1) == id(obj2)
<snip>
> (Think of id as memory adresses.)

Which means that "is" comparisons in general will be faster than == 
comparisons. According to PEP8 (python programming style guidelines) you should 
use 'is' when comparing to singletons like None. I take this to also include 
constants and such. That allows us to take short cuts through known terrain, 
such as in the massive_computations function below:

--------------------------------------------------------------
import time

class LotsOfData(object):
     def __init__(self, *data):
         self.data = data
     def __eq__(self, o):
         time.sleep(2) # time consuming computations...
         return self.data == o.data

KNOWN_DATA = LotsOfData(1,2)
same_data = KNOWN_DATA
equal_data = LotsOfData(1,2)
other_data = LotsOfData(2,3)

def massive_computations(data = KNOWN_DATA):
     if data is KNOWN_DATA:
         return "very quick answer"
     elif data == KNOWN_DATA:
         return "quick answer"
     else:
         time.sleep(10) # time consuming computations...
     return "slow answer"

print "Here we go!"
print massive_computations()
print massive_computations(same_data)
print massive_computations(equal_data)
print massive_computations(other_data)
print "Done."
--------------------------------------------------------------

Cheers,
Joel



More information about the Python-list mailing list