pydoc vs. non-def'd methods

Steven D'Aprano steve at pearwood.info
Thu Aug 22 02:39:48 EDT 2013


On Thu, 22 Aug 2013 05:13:03 +0000, Dan Sommers wrote:

> Greetings,
> 
> I'm hava a class in which there are two equally useful names for one
> method.  Consider this design (there are other approaches, but that's
> not what my question is about):

Generally though, one name will be the canonical or preferred name, and 
the other merely an alias. That being the case, it's reasonable for the 
alias to be "second class" in some fashion, as you show below.

 
> class Spam1:
> 
>     def eggs(self):
>         '''Return the Meaning of Life.'''
>         return 42
> 
>     ham = eggs
> 
> help(Spam1) shows that ham = eggs(self), which isn't all bad, but it
> could be better.  help(Spam1.ham) shows the help for eggs; I know why,
> but this could be better as well.

I'm not entirely sure how it could possibly be better. Since ham is just 
another name for eggs, it makes sense that they show the same docstring.


> And in any case, eggs looks somehow
> better than ham, because eggs has its own def statement and ham doesn't.

I don't think I agree, but perhaps that's just an aesthetic judgement 
where we disagree.

[...]
> So is there a clean way to define SpamN such that help(SpamN),
> help(SpamN.ham), and help(SpamN.eggs) all do the Right Thing, and the
> symmetry of ham and eggs is perfectly obvious to the most casual
> observer?

class Spam:
    def eggs(self):
        """eggs docstring"""
        return "ham and eggs"
    def ham(self):
        return self.eggs()
    ham.__doc__ = eggs.__doc__.replace('eggs', 'ham')

This allows you two distinct docstrings, at the cost of duplicating the 
information in them. Spam.ham will be a *tiny* bit less efficient, due to 
the extra method call, but if you're worried about that, you're probably 
up to no good :-)

But really, I would find that a confusing API. I would wonder what subtle 
difference in semantics there was between ham and eggs. I would much 
prefer to see that ham was just an alias:

class Spam:
    def eggs(self):
        """eggs docstring"""
        pass
    ham = eggs


which brings us back to the beginning of your post :-)

-- 
Steven



More information about the Python-list mailing list