Unexpected behaviour of getattr(obj, __dict__)

Terry Reedy tjreedy at udel.edu
Tue Feb 14 22:24:12 EST 2006


"Carl Banks" <invalidemail at aerojockey.com> wrote in message 
news:1139920307.858786.20310 at g44g2000cwa.googlegroups.com...
> But wait, it gets weirder.

Not weird at all.  Just an artifact of CPython's storage recycling 
algorithm.

>>>> id(Parrot.f) == id(Parrot.f)
> True
>>>> id(Parrot.__dict__) == id(Parrot.__dict__)
> True

A wrapper is created and passed to id() which returns an int object while 
releasing the wrapper back to the free list.  Then another wrapper is 
created in the same chunk of memory and passed to id, which returns an int 
of the same value for comparison.  The language ref only guarantees 
uniqueness of ids at any particular instant and allows reuse of ids of 
deallocated objects.

I half seriously think the lib ref entry for id() should have a warning 
that naive use can mislead.

> But that's not all.  Redefine Parrot as:
>
> class Parrot(object):
>    def f(self): pass
>    def g(self): pass
>
> Then,
>
>>>> id(Parrot.f) == id(Parrot.g)
> True

Same thing.  The wrapper content is not relevant as long as it uses the 
same memory block.

Terry Jan Reedy








More information about the Python-list mailing list