[Python-3000] UPDATED: PEP 3138- String representation in Python 3000
Nick Coghlan
ncoghlan at gmail.com
Tue May 27 10:13:39 CEST 2008
Oleg Broytmann wrote:
> str(container) not calling str() on items is at least a strange and
> unexpected behaviour, if not a bug.
I have no problem at all with people calling this behaviour surprising
and unexpected, but I'm not happy with them calling it a bug without
being challenged, since there are very good reasons for it working the
way it does.
str([1, 2, 3]), str(list("123")) and str(["1, 2, 3"]) should all produce
distinctive output: calling repr() on container contents achieves this,
calling str() does not.
Strings are a good example of this ambiguity problem, but there are
others, such as Decimal objects which can be indistinguishable from
normal floats and integers when printed, but definitely aren't
interchangeable with them:
>>> x = [1, 2, 3, 1.0, 2.0, 3.0]
>>> y = map(Decimal, [1, 2, 3, '1.0', '2.0', '3.0'])
>>> x
[1, 2, 3, 1.0, 2.0, 3.0]
>>> y
[Decimal("1"), Decimal("2"), Decimal("3"), Decimal("1.0"),
Decimal("2.0"), Decimal("3.0")]
>>> x == y
False
The reason for the inequality is fairly obvious given a repr() based
output for the containers (1.0 != Decimal('1.0') by design), but how big
would the potential for confusion be if str() on containers invoked
str() on their contents:
>>> print '[%s]' % ', '.join(map(str, x))
[1, 2, 3, 1.0, 2.0, 3.0]
>>> print '[%s]' % ', '.join(map(str, y))
[1, 2, 3, 1.0, 2.0, 3.0]
While it could be argued that if you want unambiguous output you should
be invoking repr() on the container instead of str(), I'm still seeing
many more downsides than upsides to the idea of making str() on the
builtin containers display their contents with str() instead of repr().
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://www.boredomandlaziness.org
More information about the Python-3000
mailing list