how to inherit docstrings?

Carl Banks pavlovevidence at gmail.com
Thu Jun 9 03:30:01 EDT 2011


On Thursday, June 9, 2011 12:13:06 AM UTC-7, Eric Snow wrote:
> On Thu, Jun 9, 2011 at 12:37 AM, Ben Finney <ben+p... at benfinney.id.au> wrote:
> > So, it's even possible to do what you ask without decorators at all:
> >
> >    class Foo(object):
> >        def frob(self):
> >            """ Frobnicate thyself. """
> >
> >    class Bar(Foo):
> >        def frob(self):
> >            pass
> >        frob.__doc__ = Foo.frob.__doc__
> >
> > Not very elegant, and involving rather too much repetition; but not
> > difficult.
> >
> 
> Yeah, definitely you can do it directly for each case.  However, the
> inelegance, repetition, and immodularity are exactly why I am pursuing
> a solution.  :)  (I included a link in the original message to
> examples of how you can already do it with metaclasses and class
> decorators too.)
> 
> I'm just looking for a way to do it with decorators in the class body
> without using metaclasses or class decorators.

The tricky part is that, inside the class body (where decorators are being evaluated) the class object doesn't exist yet, so the method decorator has no way to infer what the base classes are at that point.  A class decorator or metaclass can operate after the class object is made, but a method decorator can't.

The best you could probably do with a method decorator is something like this:

def inherit_docstring(base):
    def set_docstring(f):
        f.__doc__ = getattr(base,f.func_name).__doc__
        return f
    return set_docstring

where you have to repeat the base class every time:

class Bar(Foo):
    @inherit_docstring(Foo)
    def somefunction(self):
        pass


Carl Banks



More information about the Python-list mailing list