strange comparison result with 'is'

Terry Reedy tjreedy at udel.edu
Mon Oct 17 05:33:00 EDT 2011


On 10/17/2011 4:42 AM, Yingjie Lan wrote:
> Hi all,
>
> This is quite strange when I used the Python shell with IDLE:

Nothing to do 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.

id and is are notorious for confusing beginners. You actually created 4 
bound method objects -- but not all at the same time. IDs only only 
unique among simultaneously existing objects. It is an accident of the 
CPython implementation that two of them have the same id, even though 
they are different objects. The second line is the correct one.

> 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.

Don't show this sort of thing. Name your objects so they do not get 
garbage collected in the middle of any demonstration.

-- 
Terry Jan Reedy




More information about the Python-list mailing list