extending method descriptors

Carl Banks pavlovevidence at gmail.com
Thu Jun 25 15:30:30 EDT 2009


On Jun 25, 8:10 am, Michael Sliczniak <msliczn... at gmail.com> wrote:
> Suppose I have this:
>
> Python 2.5.1 (r251:54863, Feb  6 2009, 19:02:12)
> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.>>> class A(object):
>
> ...     __slots__ = ('x', 'y')
> ...
>
> >>> a = A()
> >>> b = A()
>
> So I am using descriptors (and I want to). I also would like to have
> methods A.x.foo(), A.x.bar(), A.y.foo(), and A.y.bar() and my idea was
> to extend member_descriptor, but it seems that I cannot:
>
> >>> type(A.x)
>
> <type 'member_descriptor'>>>> class my_descriptor(type(A.x)):
>
> ...     def foo():
> ...             return 1
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: Error when calling the metaclass bases
>     type 'member_descriptor' is not an acceptable base type


The question isn't too clear, but I can explain this error message.

A Python type defined in C must have Py_TP_BASETYPE set in its
tp_flags field, otherwise subclassing it isn't happening.

If you want such functionality, I believe it would be easiest have to
implement a MemberDescriptorWrapper class in Python that delegates to
the actual member_descriptor.  You would use it something like this:

class A(object):
    __slots__ = ['_x_internal','_y_internal']
    x = MemberDescriptorWrapper('_x_internal')
    y = MemberDescriptorWrapper('_y_internal')

MemberDescriptorWrapper class would have to implement __get__,
__set__, and __del__ methods and have them call the corresponding
methods on the slot; details are left as an exercise.


Carl Banks



More information about the Python-list mailing list