Descriptor Transparency

E

Eric Huss

I'm trying to write a descriptor (similar to the EiffelDescriptor example
in the Demo directory). However, I noticed an odd behavior that
descriptors written in pure Python mask the underlying object they are
wrapping, whereas the descriptors written in C do not.

For example, taking the code from
http://users.rcn.com/python/download/Descriptor.htm which implements what
one would think is a straightforward implementation:

class ClassMethod(object):
"Emulate PyClassMethod_Type() in Objects/funcobject.c"

def __init__(self, f):
self.f = f

def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
def newfunc(*args):
return self.f(klass, *args)
return newfunc

class MyClass(object):

def c_method_1(k, foo):
"some docstring"
print 'c_method_1: %r %r' % (k, foo)
c_method_1 = ClassMethod(c_method_1)

def c_method_2(k, foo):
"some docstring"
print 'c_method_2: %r %r' % (k, foo)
c_method_2 = classmethod(c_method_2)

You can see that the Python version does not behave the same as the C
version:
some docstring

I have seen some people manually assign the __doc__ attribute to match the
method they are wrapping (above in the __get__ method it would be
newfunc.__doc__ = self.f.__doc__ before the return). However, this
extends further into introspection:
import inspect
print inspect.getargspec(MyClass.c_method_1) ([], 'args', None, None)
print inspect.getargspec(MyClass.c_method_2)
(['k', 'foo'], None, None, None)

SO, my question is, is it possible to make a simple descriptor in Python
that has the same behavior as one implemented in C? Or, at least a way
that does not require a very large amount of emulation code. ;)

-Eric
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,585
Members
45,080
Latest member
mikkipirss

Latest Threads

Top