[Python-Dev] Re: [Python-checkins] python/dist/src/Objects stringobject.c,2.171,2.172
Guido van Rossum
guido@python.org
Sun, 28 Jul 2002 22:40:35 -0400
> > The intent was to convert an int/long to a double in the case of
> > '%g' et al and from a double to an int in the case of '%d'.
>
> Are you sure the latter part of that is a good idea? As a general
> principle, I don't think float->int conversions should be done
> automatically. What is the Python philosophy on that?
I fully agree, but unfortunately, in a dark past, I was given a patch
that did many good things, but as a side effect, made the PyArg_Parse*
family silently truncate floats to ints. Two examples:
>>> "%d" % 3.14
'3'
>>> a = []
>>> a.insert(0.9, 42)
>>> a
[42]
>>>
I find the second example more aggravating than the first. This
touches upon a recent discussion, where one of the suggestions was to
use __index__ rather than __int__ in this case. I think that's not
the right solution; perhaps instead, floats and float-like types
should support __truncate__ and __round__ to convert them to ints in
certain ways. (Of course then we can argue about whether to round to
even, and what to do if the float is so large that its smallest unit
of precision is larger than one.)
--Guido van Rossum (home page: http://www.python.org/~guido/)