Using __repr__ or __str__ for own printable class?
Steven Taschuk
staschuk at telusplanet.net
Fri Apr 25 18:39:01 EDT 2003
Quoth I:
[...]
> ... How about this? (Draft.)
>
> __repr__(self)
>
> Called by the repr() built-in function and by string conversions
[...]
I've submitted a documentation patch for the __str__ and __repr__
docs, following ideas discussed in this thread:
<http://www.python.org/sf/727789>
I solicit comments. (The __repr__ blurb is much the same as that
in the previous post; I've fiddled more extensively with the
__str__ blurb.)
__repr__(self)
Called by the repr() built-in function and by string conversions
(reverse quotes) to compute a string representation of an object.
The return value must be a string object.
The primary audience of this representation is programmers seeking
detailed information about the object for debugging or inspection
purposes; thus it is important that the representation be
information-rich and unambiguous. This representation should not
usually be parsed or manipulated by other code.
In some cases the best information-rich and unambiguous
representation is a Python expression which evaluates to the
object, that is, for eval(repr(x)) to return an object which is
equal to x (given an appropriate environment). For example, the
built-in numeric types all have such __repr__() implementations,
as do the built-in sequence and mapping types (except for cases in
which a container contains itself). Where such a representation
is infeasible or undesirable, this method should return a string
of the form <...some useful description...>.
If a class defines __repr__() but not __str__(), then __repr__()
is also used when __str__() would otherwise be called.
__str__(self)
Called by the str() built-in function and by the print statement
to compute a string representation of an object. The return value
must be a string object.
This differs from __repr__() in that it does not specifically
serve the purpose of providing a programmer with detailed
information about the object; it may provide a string
representation of the object for other purposes, as appropriate to
the object. Such purposes include display to an application
end-user, reference in an application log for administrators, or
providing a string to other code which requires one -- in general,
purposes for which the programmer-oriented information of
__repr__() is not appropriate.
--
Steven Taschuk staschuk at telusplanet.net
Every public frenzy produces legislation purporting to address it.
(Kinsley's Law)
More information about the Python-list
mailing list