__str__ vs. __repr__

Bernhard Herzog herzog at online.de
Thu Nov 4 12:27:57 CET 1999


Guido van Rossum <guido at CNRI.Reston.VA.US> writes:

> It's a separate dilemma from the other examples.  My problem here is
> that I hate to make assumptions about the character set in use.  How
> do I know that '\237' is unprintable but '\241' is a printable
> character?  How do I know that the latter is an upside-down
> exclamation point?  Should I really assume stdout is capable of
> displaying Latin-1?  Strictly, the str() function doesn't even know
> that it's output is going to stdout.  I suppose I could use isprint(),
> and then François could use the locale module in his $PYTHONSTARTUP
> file to make it do the right thing.  Is that good enough?  (I just
> tried this briefly.  It seems that somehow the locale module doesn't
> affect this?!?!
> 
> I still think that ['a', 'b'] should be displayed like that, and not
> like [a, b].  I'm not sure what that to do about a dict of Rat()
> items, except perhaps giving up on the fiction that __repr__() should
> return something expression-like for user-defined classes...
> 
> Any suggestions?

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.

If somebody want str instead they can put

import __builtin__
__builtin__.__format__ == str

in their $PYTHONSTARTUP file.

This scheme even allows for more fancy formatting like not escaping
printable chars in latin1 if the user wants it.


[1] the name __format__ is perhaps a bit too generic, but something more
descriptive like __interactive_repr__ may be a bit awkward, but then
again you don't normally call it manually.

-- 
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