Using __repr__ or __str__ for own printable class?

Donn Cave donn at u.washington.edu
Wed Apr 16 18:39:56 EDT 2003


Quoth Tim Peters <tim.one at comcast.net>:
| [Donn Cave]
|> But the idea that repr should be the function that conveys that
|> "whole truth" is suspiciously consistent with the marshalling idea.
|
| Indeed, the marshal module uses repr() to encode floats in code objects.
| The idea behind __repr__ seems prettly clear in the docs:
|
|     http://www.python.org/doc/current/ref/customization.html
|
|     __repr__(self)
|     Called by the repr() built-in function and by string conversions
|     (reverse quotes) to compute the ``official'' string representation of
|     an object.  If at all possible, this should look like a valid Python
|     expression that could be used to recreate an object with the same
|     value (given an appropriate environment).  If this is not possible, a
|     string of the form "<...some useful description...>" should be returned.
|     The return value must be a string object.   This is typically used for
|     debugging, so it is important that the representation is information-
|     rich and unambiguous.

It's clear that the docs promote this idea, but they also hint at
its half-baked quality - repr() evals to the original value, unless
it doesn't.  I don't think the idea is clear at all.

Taken together with the __str__ documentation, the original poster saw
this stuff and did not find it clear.  He learned that repr is ``official'',
vs. the ``informal'' str.  This is not explained.  The requirements for
repr conflict, and the primary one is conceded to perhaps not be practicable.
The requirements for str are on the other hand silent on its intended
application.  The only kind of clarity this documentation possesses is
when it lets you read into it what you already thought.  Not the fault
of the documentation, though, but of the unsound ideas behind it.

	Donn Cave, donn at u.washington.edu




More information about the Python-list mailing list