How to test if an object IS another object?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Jun 12 16:52:51 EDT 2005


eloff777 at yahoo.com a écrit :
> Sorry about removing my message, I posted with the wrong google
> account, I don't really want my email where those irritating spam bots
> can find it.
> 
> 
>>The most obvious way (as usual ?):
>>
>>if obj1 is obj2:
>> // your code here
> 
> 
> I immediately thought of is, and tested it in the console, but it
> didn't work quite like I expected:
> 
> 
>>foo = 3
>>bar = 3
>>zoo = foo
>>foo is zoo
> 
> True
> 
>>foo is bar
> 
> True
> 
>>zoo is bar
> 
> True
> 
> clearly foo and bar have the same value but they are different objects
> aren't they? 

Nope. They are two different names bound to the same integer object. You 
may have similar situation with strings:

 >>> s1 = "toto"
 >>> s2 = "toto"
 >>> s1 is s2
True

This is an application of the lightweight pattern. The Python 
interpreter reuse the same "value object" to avoid memory clutter. Since 
ints and strings are immutable, this is perfectly safe (but yet 
confusing when you're not aware of this).


> Yet applying the is operator yields True.

Yes. But now you know why !-)

And don't worry, this is quite unlikely that it will cause you any 
trouble in real code.



More information about the Python-list mailing list