Why isn't this a bug?

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Mon Jul 8 17:25:22 EDT 2002


Russell Blau <russblau at hotmail.com> wrote:
>>>> c = 2/5.
>>>> str(c)
>'0.4'
>>>> str((c,))
>'(0.40000000000000002,)'

>If this is not a bug, however, it does raise a question about the design of
>the language.  Granted, I suppose one *could* define the operation of the
>built-in function str() so that exactly the same value can result in
>different string representations depending on the context in which the value
>is found (i.e., a long that is inside a list "looks" different than one that
>is not inside a list); then, the output shown above is not a "bug" but is
>the way the feature was designed to operate.  But why define your language
>in such a way as to produce inconsistent output?  I don't see any value in
>doing so, and it seems vaguely un-Pythonic (although I admit my
>Pythonic-ness expertise is very limited).

Python has two levels of object-to-string conversions.

The 'str' is often too vague - it cannot distinguish between 2.4 and '2.4'.
This is not a bug - it has to make every string a fixed point (str(s)==s).

The 'repr' is often too precise - it shows 2.4 as 2.3999999999999999.  This
is not a bug - it needs to have 'eval' as an inverse on simple objects.

What is called for in most situations, and expected by most newbies, is a
level of display that is somewhat in between - it shows 2.4 as 2.4 and '2.4'
as '2.4'.  

>>> 2.4, '2.4', [2.4, '2.4']
(2.4, '2.4', [2.4, '2.4'])
>>> print 2.4, '2.4', [2.4, '2.4']
2.4 '2.4' [2.4, '2.4']

This is not hard to do (see below), but there is a view that the need is not
great enough to warrant one more level of object-to-string conversion.

>Anyway, if anyone is interested in *changing* this "feature" in a future
>version, I will point out that it can be done fairly easily by adding
>methods called "list_str" "tuplestr" and "dict_str" to the files
>listobject.c, tupleobject.c, and dictobject.c, respectively.  Each method
>would be identical to the currently-defined methods "list_repr" "tuplerepr"
>and "dict_repr" except that all calls to PyObject_Repr would be replaced by
>calls to PyObject_Str.  

Simply changing 'list_repr' to 'list_str' alone is not good enough - it will
not preserve the distinction between strings and numbers.

Sometime ago I made a patch that adds a function 'disp' and magic method
'__disp__' to handle this functionality.  Altogether 48 files need to be
changed, most only adding one item in a struct.

If there is a concensus that this is worth it, I'll try to sell it to
Python-dev.

Huaiyu



More information about the Python-list mailing list