[Python-Dev] What if we didn't have repr?

Nick Coghlan ncoghlan at gmail.com
Mon May 20 05:22:34 CEST 2013

On Mon, May 20, 2013 at 11:46 AM, Guido van Rossum <guido at python.org> wrote:
> On Sun, May 19, 2013 at 4:27 PM, Gregory P. Smith <greg at krypto.org> wrote:
>> Now you've got me wondering what Python would be like if repr, `` and
>> __repr__ never existed as language features. Upon first thoughts, I actually
>> don't see much downside (no, i'm not advocating making that change).
>> Something to ponder.
> I have pondered it many times, although usually in the form "Why do we
> need both str and repr?"


> So it looks like we really need both str(x) and repr(x). But maybe we
> only need the __repr__ protocol? str(x) could just special-case its
> own type, and use repr(x) (or x.__repr__(), which is the same) in all
> other cases. The __repr__() method on the string type would do just
> what it does today. But there would not be a __str__() protocol at
> all.

In my own code, I tend to map "__repr__" to either object identity
(the classic "<unevalable-info>" format) or object reconstruction (the
not-quite-as-classic-but-still-popular "ClassName(constructor_args)"
format). I then tend to use "__str__" to emit something that matches
any equivalence classes defined through "__eq__".

This way of thinking about it does correlate with the "for developers"
and "for end user" distinction, but without needing to think about it
in those terms.

However, even that approach has its limitations, and I offer the
existence of both the pprint module and the "__format__" protocol as
evidence, along with the multitude of context specific conversion and
escaping functions. In many respects, conversion of arbitrary objects
to context-appropriate strings is a signature use case for single
dispatch generic functions.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list