Pragmatics of the standard is() function

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Nov 28 07:57:16 EST 2011


candide wrote:
> In which cases should we use the is() function ? The is() function 
> compares identity of objects rather than values so I was wondering in 
> which circumstances comparing identities of objects is really vital.
>> Examining well reputated Python source code, I realize that is() 
> function is mainly used in the following set form :
>> spam is None
>> But how much "spam is None" is different from "spam == None" ?
>>>> is() function makes comparaison of (abstract representation of) 
> adresses of objects in memory. Comparing addresses of objects is a low 
> level feature performed by low level langages such as C but seldom 
> needed in high level languages like Python, isn'it ?
I remember meeting a use case where testing identity is required, when 
you are searching for an instance containing a specific object:
class Someone:
 def __init__(self, name, car):
 self.name = name
 self.car = car
class Car:
 def __init__(self, brand):
 self.brand = brand
 def __eq__(self, other):
 return self.brand == other.brand
people = { 'bob':Someone('bob', Car('chrys')), 'cindy': Someone('cindy', 
Car('Volk')), 'carlos':Someone('carlos', Car('Volk'))}
aCar = people['carlos'].car
print "people owning a Volk car", [ people[ppl].name for ppl in people 
if people[ppl].car == Car('Volk')]
print "people owning Carlos's car", [ people[ppl].name for ppl in people 
if people[ppl].car is aCar]
people owning a Volk car ['carlos', 'cindy']
people owning Carlos's car ['carlos']
JM


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /