Currently, the reprlib module [1] offers an "alternate repr()
implementation", and focuses mainly on guarding the length of the
returned string. I propose to broaden its scope slightly and make it
the place to add helper functions for writing __repr__(), and to add
one such function.

A dataclass automatically generates a __repr__ method (unless you ask
it not to).

@dataclasses.dataclass
class Spam:
    quality: int
    recipe: str
    ham: complex

>>> Spam(75, "<censored>", 1j)
Spam(quality=75, recipe='<censored>', ham=1j)

For non-dataclass classes, it would be extremely helpful to have an
easy helper function available:

class Spam:
    def __repr__(self):
        return reprlib.kwargs(self, ["quality", "recipe", "ham"])

The implementation for this function would be very similar to what
dataclasses already do:

# in reprlib.py
def kwargs(obj, attrs):
    attrs = [f"{a}={getattr(obj, a)!r}" for a in attrs]
    return f"{obj.__class__.__qualname__}({", ".join(attrs)})"

A similar function for positional args would be equally easy.

Bikeshedding opportunity: Should it be legal to omit the attrs
parameter, and have it use __slots__ or fall back to dir(obj) ?

ChrisA

[1] https://docs.python.org/3/library/reprlib.html
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/37UNEDRXSM6CBF3PXWZEF2TNSYYUREBO/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to