[Python-ideas] Compact repr operator (i.e., __short_repr__)
Chris Barker
chris.barker at noaa.gov
Mon Feb 8 18:43:58 EST 2016
On Mon, Feb 8, 2016 at 3:36 PM, Mahmoud Hashemi <mahmoud at hatnote.com> wrote:
> 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.
>
numpy as realized this, and produced a __repr__ (and __str__) that
truncates:
In [*26*]: len(arr)
Out[*26*]: 100000
In [*27*]: repr(arr)
Out[*27*]: 'array([ 0.00000000e+00, 1.00001000e-02, 2.00002000e-02,
...,\n 9.99980000e+02, 9.99990000e+02, 1.00000000e+03])'
I"m not sure that a full-sized repr is ever useful, so this seems fine to
me.
I wonder how often anyone actually counts on eval(repr(obj)) == obj ?
In short, I don't see that this would be all that useful.
-CHB
> 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
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160208/d524157d/attachment-0001.html>
More information about the Python-ideas
mailing list