[Python-Dev] PEP 257 and __init__
Andrew Barnert
abarnert at yahoo.com
Tue Dec 29 14:38:53 EST 2015
On Dec 29, 2015, at 10:27, Facundo Batista <facundobatista at gmail.com> wrote:
> I was reading PEP 257 and it says that all public methods from a class
> (including __init__) should have a docstring.
>
> Why __init__?
>
> It's behaviour is well defined (inits the instance), and the
> initialization parameters should be described in the class' docstring
> itself, right?
Isn't the same thing true for every special method? There are lots of classes where __add___ just says "a.__add__(b) = a + b" or (better following the PEP) "Return self + value." But, in the rare case where the semantics of "a + b" are a little tricky (think of "a / b" for pathlib.Path), where else could you put it but __add__?
Similarly, for most classes, there's only one of __init__ or __new__, and the construction/initialization semantics are simple enough to describe in one line of the class docstring--but when things are more complicated and need to be documented, where else would you put it?
Meanwhile, the useless one-liner docstrings for these methods aren't usually a problem except in trivial classes--and in trivial classes, I usually just don't bother. You can violate PEP 257 when it makes sense, just like PEP 8. They're just guidelines, not iron-clad rules.
Unless you're working on a project that insists that we must follow those guidelines, usually for some good reason like having lots of devs who are more experienced in other languages and whose instinctive "taste" isn't sufficiently Pythonic. And for that use case, keeping the rules as simple as possible is probably helpful. Better to have one wasted line in every file than to have an extra rule that all those JS developers have to remember when they're working in Python.
More information about the Python-Dev
mailing list