how to inherit docstrings?

Ben Finney ben+python at benfinney.id.au
Fri Jun 10 01:18:34 EDT 2011


Carl Banks <pavlovevidence at gmail.com> writes:

> On Thursday, June 9, 2011 7:37:19 PM UTC-7, Eric Snow wrote:
> > When I write ABCs to capture an interface, I usually put the
> > documentation in the docstrings there. Then when I implement I want
> > to inherit the docstrings. Implicit docstring inheritance for
> > abstract base classes would meet my needs.
>
> Do all the subclasses do exactly the same thing? What's the use of a
> docstring if it doesn't document what the function does?

The docstring should document the object (module, class, or function) in
a way useful for the user of that API.

Differing implementations don't necessarily make for differing external
behaviour. In those cases where the external behaviour can be adequately
described by exactly the same docstring as the parent class's method,
it's tedious and error-prone to repeat or duplicate the docstring.

> class Shape(object):
>     def draw(self):
>         "Draw a shape"
>         raise NotImplementedError

class Shape(object):
    """ Abstract class for shapes. """

    def draw(self):
        """ Draw this shape. """
        raise NotImplementedError

> class Triangle(Shape):
>     def draw(self):
>         print "Triangle"

class Triangle(Shape):
    """ A three-sided polygon. """

    def draw(self):
        trace_three_sided_polygon()

> class Square(Shape):
>     def draw(self):
>         print "Square"

class Square(Shape):
    """ An equal-sided quadrilateral polygon. """

    def draw(self):
        trace_quadrilateral_with_equal_sides()

> x = random.choice([Triange(),Square()])
> print x.draw.__doc__  # prints "Draws a shape"

x = random.choice([Triangle(), Square()])
print x.draw.__doc__    # => "Draw this shape."

> Quick, what shape is x.draw() going to draw?

print x.__doc__    # => " An equal-sided quadrilateral polygon. "

> Shouldn't your docstring say what the method is going to do?

There's nothing wrong with the docstring for a method referring to the
context within which the method is defined.

> Whenever somebody overrides a method to do something different, the
> inherited docstring will be insufficient (as in your ABC example) or
> wrong.

I hope the above demonstrates that your assertion is untrue. Every
single method on a class doesn't need to specify the full context; a
docstring that requires the reader to know what class the method belongs
to is fine.

-- 
 \         “In any great organization it is far, far safer to be wrong |
  `\          with the majority than to be right alone.” —John Kenneth |
_o__)                                            Galbraith, 1989-07-28 |
Ben Finney



More information about the Python-list mailing list