Account Options

  1. Sign in
The old Google Groups will be going away soon, but your browser is incompatible with the new version.
Google Groups Home
« Groups Home
Message from discussion Override a method but inherit the docstring
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
 
From:
To:
Cc:
Followup To:
Add Cc | Add Followup-to | Edit Subject
Subject:
Validation:
For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon. Listen and type the numbers you hear
 
Rhodri James  
View profile  
 More options Jul 16 2009, 9:31 pm
Newsgroups: comp.lang.python
From: "Rhodri James" <rho...@wildebst.demon.co.uk>
Date: Fri, 17 Jul 2009 02:31:43 +0100
Local: Thurs, Jul 16 2009 9:31 pm
Subject: Re: Override a method but inherit the docstring
On Fri, 17 Jul 2009 02:01:49 +0100, Ben Finney  

<ben+pyt...@benfinney.id.au> 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),

Not really.  Consider the case of BarGonk being a subclass of FooGonk
and BazGonk; which docstring would you wish to inherit?

> puts the docstring assignment awkwardly after the end
> of the method instead of at the beginning where docstrings normally go,
> and reads poorly besides.

Sounds like a job for a decorator!

(This is probably unbelievably ugly and unwise, since I don't use
decorators at all often.)

def copydoc(cls):
     def _fn(fn):
         if fn.__name__ in cls.__dict__:
             fn.__doc__ = cls.__dict__[fn.__name__].__doc__
         return fn
     return _fn

class BarGonk(FooGonk):
     @copydoc(FooGonk)
     def frobnicate(self):
         special_implementation(self.warble)

--
Rhodri James *-* Wildebeest Herder to the Masses


 
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.