Welcome, guest | Sign In | My Account | Store | Cart

In many cases, a subclass overrides a method in a parent class, just to change its implementation; in such cases, it would be nice to preserve the overridden method's docstring. The decorator below can be used to achieve this without explicit reference to the parent class. It does this by replacing the function with a descriptor, which accesses the parent class when the method is accessed as an attribute.

Python, 66 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
doc_inherit decorator

Usage:

class Foo(object):
    def foo(self):
        "Frobber"
        pass

class Bar(Foo):
    @doc_inherit
    def foo(self):
        pass 

Now, Bar.foo.__doc__ == Bar().foo.__doc__ == Foo.foo.__doc__ == "Frobber"
"""

from functools import wraps

class DocInherit(object):
    """
    Docstring inheriting method descriptor

    The class itself is also used as a decorator
    """

    def __init__(self, mthd):
        self.mthd = mthd
        self.name = mthd.__name__

    def __get__(self, obj, cls):
        if obj:
            return self.get_with_inst(obj, cls)
        else:
            return self.get_no_inst(cls)

    def get_with_inst(self, obj, cls):

        overridden = getattr(super(cls, obj), self.name, None)

        @wraps(self.mthd, assigned=('__name__','__module__'))
        def f(*args, **kwargs):
            return self.mthd(obj, *args, **kwargs)

        return self.use_parent_doc(f, overridden)

    def get_no_inst(self, cls):

        for parent in cls.__mro__[1:]:
            overridden = getattr(parent, self.name, None)
            if overridden: break

        @wraps(self.mthd, assigned=('__name__','__module__'))
        def f(*args, **kwargs):
            return self.mthd(*args, **kwargs)

        return self.use_parent_doc(f, overridden)

    def use_parent_doc(self, func, source):
        if source is None:
            raise NameError, ("Can't find '%s' in parents"%self.name)
        func.__doc__ = source.__doc__
        return func

doc_inherit = DocInherit 

The question of how to do this was brought up by Ben Finney on c.l.py where several alternative methods have been suggested.

There is only one point I can add to the discussion in the thread: The way a callable-returning descriptor needs to build slightly different functions for the access-through-class and access-through-instance cases is a sort of a pattern, and I would like to have a way to abstract it away.

2 comments

nikratio 10 years, 9 months ago  # | flag

I'd like to point out yet another different solution to this problem that I've come up with: http://code.activestate.com/recipes/578587-inherit-method-docstrings-without-breaking-decorat/. The advantage of that recipe is that the methods don't need to become descriptors, and that the inherited docstrings are also available to other function decorators.

Shai Berger (author) 10 years, 9 months ago  # | flag

True. Python 3 metaclasses are stronger. This recipe's advantage is that it works with Python 2.