I have an OO hierarchy with docstrings that take as much maintenance as the code itself. E.g.,
class Swallow(object):
def airspeed(self):
"""Returns the airspeed (unladen)"""
raise NotImplementedError
class AfricanSwallow(Swallow):
def airspeed(self):
# whatever
Now, the problem is that AfricanSwallow.airspeed
does not inherit the superclass method's docstring. I know I can keep the docstring using the template method pattern, i.e.
class Swallow(object):
def airspeed(self):
"""Returns the airspeed (unladen)"""
return self._ask_arthur()
and implementing _ask_arthur
in each subclass. However, I was wondering whether there's another way to have docstrings be inherited, perhaps some decorator that I hadn't discovered yet?
F.Y.I for people just now stumbling on this topic: As of Python 3.5, inspect.getdoc automatically retrieves docstrings from the inheritance hierarchy.
The responses above are thus useful for Python 2, or if you want to be more creative with merging the docstrings of parents and children.
I've also created some lightweight tools for docstring inheritance. These support some nice default docstring styles (numpy, google, reST) out of the box. You can easily use your own docstring style as well
The following adaptation also handles properties and mixin classes. I also came across a situation where I had to use
func.__func__
(for "instancemethod"s), but I'm not completely sure why the other solutions didn't encouter that problem.Write a function in a class-decorator style to do the copying for you. In Python2.5, you can apply it directly after the class is created. In later versions, you can apply with the @decorator notation.
Here's a first cut at how to do it:
In newer Python versions, the last part is even more simple and beautiful:
This is a Pythonic technique that exactly matches the design of existing tools in the standard library. For example, the functools.total_ordering class decorator add missing rich comparison methods to classes. And for another example, the functools.wraps decorator copies metadata from one function to another.
This is a variation on Paul McGuire's DocStringInheritor metaclass.