__str__ vs. __repr__
Bernhard Herzog
herzog at online.de
Fri Nov 5 06:53:51 EST 1999
Guido van Rossum <guido at cnri.reston.va.us> writes:
> Bernhard Herzog <herzog at online.de> writes:
>
> > How about a hook function a la __import__? I.e. have a function
> > __format__ [1] in __builtin__ that is bound to repr by default. Whenever
> > Python prints the result of an expression in interactive mode, it calls
> > __format__ with the result as parameter and expects it to return a
> > string ready for printing.
>
> Brilliant!
Glad you like it!
> The default function could do all the current built-in
> magic -- print nothing if it's None, assign it to builtin _, and so
> on.
It seems to me that assigning to _ and printing the result are two
separate things. IMO, the hook function should only do the formatting,
the assignment could still be hardwired in the interpreter loop. Pseudo
code:
while 1:
statement = read_statement()
if not statement:
break
result = run_statement(statement)
__builtin__._ = result
if result is not None:
print __format__(result)
> I wonder if it would have to have a __magic__ name? It could be
> called display and it could be documented and usable in
> non-interactive programs as well. Or am I getting carried away?
> (Possibly the habit if assigning to _ and suppressing None would make
> the default display() function a bit clumsy to use.)
Well, I chose a magic name because it's called in special circumstances.
Calling it display is fine with me, especially if it really does only
formatting and no assignment to _ and no special-casing of None, as is
assumed in my pseudo code above. Such a version of display would also be
usable in non-interactive programs.
One could take this even further by moving the entire interactive mode
to a python module. Most of the python code for that is already
available in the code.py module, IIRC.
--
Bernhard Herzog | Sketch, a drawing program for Unix
herzog at online.de | http://www.online.de/home/sketch/
More information about the Python-list
mailing list