Python – Sharing Docstrings Between Similar Functions

documentationprogramming practicespython

Assuming we have different classes with methods that possess the exact same description, however execute code a bit differently for the same return type.

class Foo:
    """This is the Foo class Docstring. It is a type of Bar source."""
    def getBar(self,pos):
        """
        This is the Bar method. 
        It calculates and returns the Bar field effect generated 
        by this source based on `pos`
        """   
        effect = pos + 1 
        return effect

class Waldo:
    """This is the Waldo class Docstring. It's also a type of Bar source."""
    def getBar(self,pos):
        """
        This is the Bar method. 
        It calculates and returns the Bar field effect generated 
        by this source based on `pos`
        """   
        effect = pos + 2 
        return effect

This is a problem because, assuming there are many Bar sources, if one changes the description for getBar() they'll have to repeat the change for all the sources.

How could one make it so there's a single Docstring shared between both or more of these, having it so a change in Foo.getBar() would change the description of Waldo.getBar() for tooltips?

A way of restructuring or overriding in order to achieve the same effect would also be welcome.


I've tried the __doc__+=Foo.getBar().__doc__ approach in this question but it seems unreliable (using an environment like Spyder for instance, it recognizes it as a local variable).

Best Answer

Different tools access docstrings differently. For example, having a common base class that provides this docstring may be sufficient for some tools but not others.

The most general approach would be to define a functools.wraps() like decorator that copies the docstring of a function, e.g.:

def is_documented_by(original):
  def wrapper(target):
    target.__doc__ = original.__doc__
    return target
  return wrapper

class Waldo:
  @is_documented_by(Foo.getBar)
  def getBar():
    ...

But since this requires executing the Python code, static analyzers like Pylint may not like this. The best solution depends on the tools you are going to use.

Related Topic