[Python-ideas] Compact repr operator (i.e., __short_repr__)

Mahmoud Hashemi mahmoud at hatnote.com
Mon Feb 8 18:36:26 EST 2016


I was curious if what kind of interest there would be in adding an
overridable method to types to allow getting back a repr, but a predictably
short one.

The motivation is that there are many cases where producing the full,
round-trippable repr is possible, but would take up significant resources
or be too huge to be useful for human consumption.

The built-in [reprlib module][1] certainly shows there's an interest for
many built-in types, and I think arguably that same functionality is
desirable for user types.

As mentioned in the subject a possible API could be:

class ValueObject(object):
    def __init__(self, content):
        self.content = content

    def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, self.content)

    def __short_repr__(self, size=None, depth=None):
        # TODO: should interpretation of size/depth be casual or strict?
        if size and len(self.content) > size:
            short_content = self.content[:size] + '...'
        else:
            pass  # TODO: could just return normal repr possibly
        return '<%s content=%r)' % (self.__class__.__name__, short_content)

Without something like this, there's no way to ask an object if it's repr
is of manageable length, or how its repr could be meaningfully shortened.
Usually I just chop out the middle and add an ellipsis, but as for the time
spent generating that middle, I'll never get those cycles back.

Anyways, thanks for your attention, and happy Monday to all!

Mahmoud
https://github.com/mahmoud
https://twitter.com/mhashemi
http://sedimental.org

[1]: https://docs.python.org/2/library/functions.html#func-repr
[2]: https://docs.python.org/3.4/library/reprlib.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160208/f58fa9d2/attachment.html>


More information about the Python-ideas mailing list