Override a method but inherit the docstring

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Jul 27 10:05:11 EDT 2009


Ben Finney wrote:
> Howdy all,
>
> The following is a common idiom::
>
>     class FooGonk(object):
>         def frobnicate(self):
>             """ Frobnicate this gonk. """
>             basic_implementation(self.wobble)
>
>     class BarGonk(FooGonk):
>         def frobnicate(self):
>             special_implementation(self.warble)
>
> The docstring for ‘FooGonk.frobnicate’ is, intentionally, perfectly
> applicable to the ‘BarGonk.frobnicate’ method also. Yet in overriding
> the method, the original docstring is not associated with it.
>
> Ideally there would be a way to specify that the docstring should be
> inherited. The best I can come up with is::
>
>     class BarGonk(FooGonk):
>         def frobnicate(self):
>             special_implementation(self.warble)
>         frobnicate.__doc__ = FooGonk.frobnicate.__doc__
>
> but that violates DRY (the association between BarGonk and FooGonk is
> being repeated), puts the docstring assignment awkwardly after the end
> of the method instead of at the beginning where docstrings normally go,
> and reads poorly besides.
>
> What is the most Pythonic, DRY-adherent, and preferably least-ugly
> approach to override a method, but have the same docstring on both
> methods?
>
>   
I am using epydoc and if the docstring is present only in the baseclass 
method, it will repeat the docstring for the child methods. So 
basically, there's nothing to do.
I've also tried within the python interpreter, and it can perfectly 
solve docstring inheritance. So why would you explicitly assign 
docstring to child methods ?

JM



More information about the Python-list mailing list