Container behaviour (was: print attitude)
donn at u.washington.edu
Tue Jul 8 18:37:35 CEST 2003
In article <mailman.1057675993.29542.python-list at python.org>,
"Batista, Facundo" <FBatista at uniFON.com.ar> wrote:
> #- Personally, I think the internal difference between str and repr hits
> #- right upon a proper difference: str is for a "reasonable"
> #- human-readable representation, and repr is for as faithful and
> #- informative a representation as possible. These both have their uses
> #- and I approve of the distinction.
> Beyond the specific utilization of str or repr, the detail that get me
> confused is:
> repr (container) => repr (elements)
> str (container) => repr (elements)
> Why cannot I, when I want the repr of a container, get the repr of its
> elements, and when I want the str of a container, get the str of its
Because that wouldn't make sense. Neither does the interpretation
of str and repr you quote, so that's not going to be much help.
str is a type conversion function. Data types that can
sensibly be converted to strings can provide a __str__
function that does that. Conversion doesn't mean that all
the information present in the original survives in the result,
only the properties that make sense in a string.
For example, you might design a sequence data type that is
a list of integer values in the range [0..255], say for the
purpose of some cryptography, and write a __str__ whose result
simply puts the same values in a string type. Or a class that
carries a list of strings might just concatenate them (cf.
But lists themselves do not have any natural conversion to
string type, so they fall back to repr. Eric did explain
why simply applying str to the elements would make an ambiguous
mess. You may be able to describe an ideal result for your
application, but there are many other potentially ideal ways
to do it and no way to say one of them makes more sense than
another. I think if I were obliged to write the __str__ function
that applies str to each element of a list, I would simply join
the strings with no separator, so str([10, 11, 12]) == '101112',
but I'm sure that would offend as many people as it pleased.
Donn Cave, donn at u.washington.edu
More information about the Python-list