[Python-Dev] Fixing _PyEval_SliceIndex so that integer-like
objects can be used
Guido van Rossum
gvanrossum at gmail.com
Fri Feb 18 22:48:16 CET 2005
> > > Would it be possible to change
> > >
> > > _PyEval_SliceIndex in ceval.c
> > >
> > > so that rather than throwing an error if the indexing object is not an
> > > integer, the code first checks to see if the object has a
> > > tp_as_number->nb_int method and calls it instead.
> > I don't think this is the right solution; since float has that method,
> > it would allow floats to be used as slice indices, but that's not
> > supposed to work (to protect yourself against irreproducible results
> > due to rounding errors).
> I wonder if floats are the special case here, not "integer like objects".
> I've never been particularly happy about the confusion between the two
> roles of int() and it's C equivalents, i.e. casting and conversion.
You're right, that's the crux of the matter; I unfortunately copied a
design mistake from C here. In Python 3000 I'd like to change this so
that floats have a __trunc__() method to return an integer (invokable
But in Python 2.x, we can't be sure that floats are the *only*
exception -- surely people who are implementing their own "float-like"
classes are copying float's example and implementing __int__ to mean
the same thing. For example, the new decimal class in Python 2.4 has a
converting/truncating __int__ method. (And despite being decimal, it's
no less approximate than float; decimal is *not* an exact numerical
So I still think it's unsafe (in Python 2.x) to accept __int__ in the
way Travis proposes.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev