[e-lang] on Python repr() vs. str()

Kragen Sitaker e-lang@mail.eros-os.org
Fri, 7 Jun 2002 20:15:20 -0400 (EDT)

MarkM had asked for clarification here.

There are two standard ways of converting an object to a string in

One is repr(), which produces output suitable for a REPL; in
particular, it unambiguously identifies the type of the object, and if
possible, it is a syntactically-valid Python expression which, if
evaluated, would produce an object equal to the object originally
passed to repr().

Lisp uses WRITE and READ where Python uses repr() and eval().

The other is str(), whose purpose is to make sure that something is a
string so you can print it.  It calls repr() if there is no str()
defined for the object, but some objects define different repr() and
str() behavior.  In particular, str(x) == x if x is already a string.

I think this is a very pleasant distinction to have.  It allows
objects to be both readably serialized and clearly displayed by
recognizing the difference in intent.  JavaScript's conversion to
string fails badly for many things, such as arrays of empty strings,
mostly because JavaScript does not have a way to recognize this

I rather wish, for security reasons, that READ wasn't eval, but it
does make it easier to read Python code that I don't have to worry
about whether (car x) represents a list or a function call.

I wrote an HTML version of repr() called htmlstr() on the theory that
HTML allows a more readable presentation.

<kragen@pobox.com>       Kragen Sitaker     <http://www.pobox.com/~kragen/>
Techno addiction. More expensive than crack, keeps you up longer than
coke, makes you fatter than pot, but hey... it's legal. 
	-- Tim Byars <tbyars@earthlink.net>