Skip to content
This repository has been archived by the owner on Nov 3, 2023. It is now read-only.

Guidance on Magic Method Docstrings #480

Open
mentalisttraceur opened this issue May 20, 2020 · 1 comment
Open

Guidance on Magic Method Docstrings #480

mentalisttraceur opened this issue May 20, 2020 · 1 comment

Comments

@mentalisttraceur
Copy link

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.

@gbroques
Copy link
Contributor

gbroques commented Aug 1, 2020

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! :)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants