Unexpected behaviour of getattr(obj, __dict__)
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Tue Feb 14 07:27:14 EST 2006
On Tue, 14 Feb 2006 04:11:52 -0800, Raymond Hettinger wrote:
> Steven D'Aprano wrote:
>> I came across this unexpected behaviour of getattr for new style classes.
>> Example:
>>
>> >>> class Parrot(object):
>> ... thing = [1,2,3]
>> ...
>> >>> getattr(Parrot, "thing") is Parrot.thing
>> True
>> >>> getattr(Parrot, "__dict__") is Parrot.__dict__
>> False
>>
>> I would have expected that the object returned by getattr would be the
>> same object as the object returned by standard attribute access.
>
> The returned object is a wrapper created on-the-fly as needed. You've
> requested two of them and each wrapper has a different object id but
> wraps an identical source.
[penny drops]
That would certainly explain it.
Is there a canonical list of attributes which are wrapped in this way? I
suppose not... it is probably the sort of thing which is subject to change
as Python evolves.
I knew methods were wrapped, but I didn't know they were wrapped on the
fly, nor did I connect the two phenomena. Thank you for the concise and
simple answer.
--
Steven.
More information about the Python-list
mailing list