Descriptor Transparency

Eric Huss e-huss at netmeridian.com
Wed Apr 27 18:44:32 EDT 2005


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:

>>> print MyClass.c_method_1.__doc__
None
>>> print MyClass.c_method_2.__doc__
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



More information about the Python-list mailing list