Why isn't this a bug?

Jonathan Hogg jonathan at onegoodidea.com
Mon Jul 8 11:06:13 EDT 2002


On 7/7/2002 21:12, in article aga7af$jsvv9$1 at ID-76829.news.dfncis.de,
"Russell Blau" <russblau at hotmail.com> wrote:

> As the above example shows, the str() built-in function represents long and
> float values one way if they are passed directly as the argument of the
> function, but a different way if they are found inside a list or tuple (or
> dict, although I didn't illustrate that above).
[...]
> Ah hah, I thought, I've found a bug.  However, I did a search on
> sourceforge.net and found that this issue (or at least part of it) had
> already been submitted as a bug and rejected!  (It was number 506741, for
> anyone who wants to look.)
[...]
> Of course, if someone would like to explain why something so simple and
> intuitive is a "bad idea," please enlighten me.  ;-)

I think the problem is that you're considering an implicit behaviour to be a
feature. The rough meaning of 'str' and 'repr' is:

    repr - return a string representation of an object (ideally such that
           the string can be 'eval'ed to re-produce the object)

    str  - convert an object into a string

For numbers, these two behaviours are easily defined. But for tuples and
lists there is no obvious behaviour for 'str'. What does it mean to turn a
tuple or a list into a string? In the absence of a defined behaviour, the
interpreter falls back on just returning 'repr' of the object.

You have to ask yourself: why am I converting a tuple into a string? Perhaps
the behaviour you want would be better written explicitly like:

>>> c = (0.5, 0.7)
>>> str(c)
'(0.5, 0.69999999999999996)'
>>> "(%s, %s)" % c
'(0.5, 0.7)'
>>> 

It's best not to rely on implicit conversions.

-import-this-ly-y'rs,

Jonathan




More information about the Python-list mailing list