[Numpy-discussion] non-integer index misfeature?
Sebastian Berg
sebastian at sipsolutions.net
Wed Dec 12 17:29:01 EST 2012
On Wed, 2012-12-12 at 20:48 +0000, Nathaniel Smith wrote:
> On Wed, Dec 12, 2012 at 8:20 PM, Ralf Gommers <ralf.gommers at gmail.com> wrote:
> >
> > On Tue, Dec 11, 2012 at 5:44 PM, Neal Becker <ndbecker2 at gmail.com> wrote:
> >>
> >> I think it's a misfeature that a floating point is silently accepted as an
> >> index. I would prefer a warning for:
> >>
> >> bins = np.arange (...)
> >>
> >> for b in bins:
> >> ...
> >> w[b] = blah
> >>
> >> when I meant:
> >>
> >> for ib,b in enumerate (bins):
> >> w[ib] = blah
> >
> >
> > Agreed. Scipy.special functions were just changed to generate warnings on
> > truncation of float inputs where ints are expected (only if truncation
> > changes the value, so 3.0 is silent and 3.1 is not).
> >
> > For numpy indexing this may not be appropriate though; checking every index
> > value used could slow things down and/or be quite disruptive.
>
> I doubt this is measurable, and it only affects people who are using
> floats as indexes, which is a risky thing to be doing in the first
> place. The only good reason to use floats as indexes is if you're
> doing floating point arithmetic to calculate indexes -- but now you're
> going to get bitten as soon as some operation returns N - epsilon
> instead of N, and gets truncated to N - 1.
>
> I'd be +1 for a patch to make numpy warn when indexing with
> non-integer floats. (Heck, I'd probably be +1 on deprecating allowing
> floating point numbers as indexes at all... it's risky as heck and
> reminding people to think about rounding can only be a good thing,
> given that risk.)
>
Personally +1 on just deprecating that stuff in the long run. Just if
someone is interested I remember seeing this comment (which applies for
the scalar case):
/*
* PyNumber_Index was introduced in Python 2.5 because of NumPy.
* http://www.python.org/dev/peps/pep-0357/
* Let's use it for indexing!
*
* Unfortunately, SciPy and possibly other code seems to rely
* on the lenient coercion. :(
*/
#if 0 /*PY_VERSION_HEX >= 0x02050000*/
PyObject *ind = PyNumber_Index(op);
if (ind != NULL) {
value = PyArray_PyIntAsIntp(ind);
Py_DECREF(ind);
}
else {
value = -1;
}
#else
and is is somewhat related. But with a long deprecation process
switching to using `__index__` would seem possible to me.
Regards,
Sebastian
> -n
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
More information about the NumPy-Discussion
mailing list