Beyond __str__ and __repr__? (Was Re: Python doesn't know how to do math?)

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Fri Apr 26 17:06:11 EDT 2002


David Bolen <db3l at fitlinxx.com> wrote:
>instead.  The default output at the interpreter is to use repr() to
>print an object, which shows the highest precision possible to best
>assure that its output could be used to re-create the object.  The
>print statement will use str() which is designed for "prettier" output
>and will do some rounding.

The current arrangement between repr and str has some shortcomings:

- nested structures use repr for elements
- repr is constrained by the desire to be inverse of eval for simple types
- default repr for instances are optimized for object id, not content
- str cannot differentiate between 2 and "2"

It appears that another display level is needed, somewhat between repr and
str.  Let's call it 'disp' here.  It is intended to be used for display in a
controlled way, esp for nested structures.

Here's what I think it should do:

- disp(0.05)    -> "0.05", just like str(0.05).
- disp("abc")   -> "'abc'", just like repr('abc').
- disp([a,b,c]) -> '['+', '.join(map(disp, [a,b,c]))+']'.
- disp(obj)     ->  obj.__disp__().

Having and additional display method also reduces the need to override
__repr__, which is the source of very confusing diagnostics when not done
right (ie, when diagnostics are needed).

Huaiyu



More information about the Python-list mailing list