strange comparison result with 'is'

Peter Otten __peter__ at web.de
Mon Oct 17 05:19:35 EDT 2011


Yingjie Lan wrote:


> This is quite strange when I used the Python shell with IDLE:
> 
>>>> x = []
>>>> id(getattr(x, 'pop')) == id(x.pop)
> 
> True
>>>> getattr(x, 'pop') is x.pop
> False
>>>>
> 
> I suppose since the two things have the same id, the 'is'-test
> should give a True value, but I get a False value.
> 
> Any particular reason for breaking this test?
> I am quite confused as I show this before a large
> audience only to find the result denies my prediction.
> 
> The python version is 3.2.2; I am not sure about other versions.

The getattr() call is just a distraction. Every x.pop attribute access 
creates a new method object. In the case of

>>> x.pop is x.pop
False

they have to reside in memory simultaneously while in the expression

>>> id(x.pop) == id(x.pop)
True

a list.pop method object is created, its id() is taken (which is actually 
its address) and then the method object is released so that its memory 
address can be reused for the second x.pop. 

So in the latter case the two method objects can (and do) share the same 
address because they don't need to exist at the same time.




More information about the Python-list mailing list