Class attributes, instances and metaclass __getattribute__

Michele Simionato michele.simionato at gmail.com
Tue Aug 8 03:10:39 EDT 2006


Pedro Werneck wrote:
> When I access a class attribute, on a class with a custom metaclass with
> a __getattribute__ method, the method is used when acessing some
> attribute directly with the class object, but not when you do it from
> the instance.
>
> <code type='prompt'>
> >>> class M(type):
> ...     def __getattribute__(cls, attr):
> ...             print cls, attr
> ...             return type.__getattribute__(cls, attr)
> ...
> >>> class C(object):
> ...     __metaclass__ = M
> ...
> >>> C.x = 'foo'
> >>> C.x
> <class '__main__.C'> x
> 'foo'
> >>> o = C()
> >>> o.x
> 'foo'
> >>>
> </code>
>
>
> Someone at freenode #python channel involved with python-dev sprint
> suggested it might be a bug, worth mentioning... to me it seems like a
> decision to avoid some problems with method and descriptors creation,
> since someone using metaclasses and custom __getattribute__ at the same
> time is asking for trouble, but... I googled for it and tried to find
> something on the list but, nothing. From the source it seems like a
> generic wrapper is used. What's the real case here ?
>
>
> Regards,
>
> --
> Pedro Werneck

To me, it seems consistent. As said in
http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/

"""The availability of metaclass attributes is not transitive; in other
words, the attributes of a metaclass are available to its instances,
but not to the instances of the instances. Just this is the main
difference between metaclasses and superclasses."""

Since this happens for real attributes, it looks natural that the same
should
happen for 'virtual' attributes implemented via '__getattr__' or
'__getattribute__'.

          Michele Simionato




More information about the Python-list mailing list