getting special from type, not instance (was Re: [Python-Dev] copy confusion)

Phillip J. Eby pje at telecommunity.com
Wed Jan 12 19:30:01 CET 2005


At 09:59 AM 1/12/05 -0800, Guido van Rossum wrote:
>We would need to introduce a new decorator so that classes overriding
>these methods can also make those methods "data descriptors", and so
>that users can define their own methods with this special behavior
>(this would be needed for __copy__, probably).

I have used this technique as a workaround in PyProtocols for __conform__ 
and __adapt__, so I know it works.  In fact, here's the implementation:

def metamethod(func):
     """Wrapper for metaclass method that might be confused w/instance 
method"""
     return property(lambda ob: func.__get__(ob,ob.__class__))

Basically, if I implement a non-slotted special method (like __copy__ or 
__getstate__) on a metaclass, I usually wrap it with this decorator in 
order to avoid the "metaconfusion" issue.

I didn't mention it because the technique had gotten somehow tagged in my 
brain as a temporary workaround until __conform__ and __adapt__ get slots 
of their own, rather than a general fix for metaconfusion.  Also, I wrote 
the above when Python 2.2 was still pretty new, so its applicability was 
somewhat limited by the fact that 2.2 didn't allow super() to work with 
data descriptors.  So, if you used it, you couldn't use super.  This 
probably isn't a problem any more, although I'm still using the super-alike 
that I wrote as a workaround, so I don't know for sure.  :)


>PS. The term "data descriptor" now feels odd, perhaps we can say "hard
>descriptors" instead. Hard descriptors have a __set__ method in
>addition to a __get__ method (though the __set__ method may always
>raise an exception, to implement a read-only attribute).

I think I'd prefer "Override descriptor" to "Hard descriptor", but either 
is better than data descriptor.  Presumably there will need to be backward 
compatibility macros in the C API, though for e.g. PyDescriptor_IsData or 
whatever it's currently called.



More information about the Python-Dev mailing list