how to inherit docstrings?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jun 10 05:51:20 EDT 2011


On Thu, 09 Jun 2011 20:36:53 -0700, Carl Banks wrote:

> x = random.choice([Triange(),Square()]) print x.draw.__doc__  # prints
> "Draws a shape"
> 
> 
> Quick, what shape is x.draw() going to draw?

That's easy... it will draw a type(x).__name__.

I think this not a terribly convincing argument. I don't particularly see 
how it is very different (worse, or better) from what you can already get 
in Python. If you don't know what x is, you might not know what it will 
do.


>>> assert issubclass(ValueError, Exception)
>>> ValueError.__doc__
'Inappropriate argument value (of correct type).'
>>> Exception.__doc__
'Common base class for all non-exit exceptions.'
>>> from random import choice
>>> x = choice([ValueError, Exception])

Quick, what will x.__doc__ print?



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

But it does say what the method does. It prints a shape, just like the 
docstring says. It might not be a terribly detailed description, but that 
counts as a quality of implementation issue, not a functional bug.


> So, I'm sorry, but I don't see this being sufficient for your use case
> for ABCs.
> 
> 
>> I'm just not clear on the
>> impact this would have for the other use cases of docstrings.
> 
> Whenever somebody overrides a method to do something different, the
> inherited docstring will be insufficient (as in your ABC example) or
> wrong.  This, I would say, is the case most of the time when overriding
> a base class method.  When this happens, the language is committing an
> error.

It's hardly a *language* error if you, the developer, writes an 
incomplete or incorrect docstring.

If you want to argue that the language shouldn't enable a failure mode of 
the developer (namely the use of an incomplete or incorrect docstring), 
well, perhaps you are right. But you are assuming that an inherited 
docstring is necessarily wrong, which is not the case. "Prints a shape", 
as in your above example, is a perfectly acceptable, if minimal, 
docstring. It might not be a *great* docstring, but it's not a wrong one.


> Put it this way: if Python doesn't automatically inherit docstrings, the
> worst that can happen is missing information.  If Python does inherit
> docstrings, it can lead to incorrect information.

This is no different from inheriting any other attribute. If your class 
inherits "attribute", you might get an invalid value unless you take 
steps to ensure it is a valid value. This failure mode doesn't cause us 
to prohibit inheritance of attributes.



-- 
Steven



More information about the Python-list mailing list