Guidance on Magic Method Docstrings
mentalisttraceur opened this issue · 1 comments
Is there any example or guide anywhere for what a __repr__
docstring ought to look like?
I think it would be nice for pydocstyle to reference some best practices for docstringing magic methods, since it complains about it by default.
Especially because it is clear what some magic methods should have in their docstring (for example, __eq__
should describe how equality is determined) but something like __repr__
is less obvious.
So far my idea is to give a summary of what the produced repr looks like, when it is or is not recursion-safe, and when it is or is not valid to eval
.
Anyway, it seems that people are likely to come to this project looking for ideas once they see the warnings about magic methods not having docstrings, so I think maybe we can get a discussion going here.
In general, a docstring that simply states the single-responsibility of the method, even if it's obvious, is probably sufficient for most cases.
There's discussion of the purpose of __repr__
on the following StackOverflow:
https://stackoverflow.com/questions/1984162/purpose-of-pythons-repr
For example, consider the docstring for the below __repr__
method of the Point
class:
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
"""Returns a representation of a Point object."""
return 'Point(x=%s, y=%s)' % (self.x, self.y)
It's simple, but it's enough to be helpful.
Of course, you'd always want to mention anything non-obvious as well.
In the case of __repr__
, can the result of repr(obj)
be passed into eval(...)
to re-instantiate or deserialize the object?
Or is __repr__
only supposed to be a friendly representation of the object for debugging purposes in unit-tests or the Python interpreter?
Are you only displaying a sub-set of the fields? Why choose to display some fields over others?
All of this could be helpful to include in the docstring.
Hopefully this helps! :)