[Numpy-discussion] Changing the behavior of (builtins.)round (via the __round__ dunder) to return an integer
Antony Lee
antony.lee at berkeley.edu
Wed Apr 13 03:42:06 EDT 2016
https://github.com/numpy/numpy/issues/3511 proposed (nearly three years
ago) to return an integer when `builtins.round` (which calls the `__round__
dunder method, and thereafter called `round` (... not to be confused with
`np.round`)) is called with a single argument. Currently, `round` returns
a floating scalar for numpy scalars, matching the Python2 behavior.
Python3 changed the behavior of `round` to return an int when it is called
with a single argument (otherwise, the return type matches the type of the
first argument). I believe this is more intuitive, and is arguably
becoming more important now that numpy is deprecating (via a
VisibleDeprecationWarning) indexing with a float: having to write
array[int(round(some_float))]
is rather awkward. (Note that I am suggesting to switch to the new
behavior regardless of the version of Python.)
Note that currently the `__round__` dunder is not implemented for arrays
(... see https://github.com/numpy/numpy/issues/6248) so it would be
feasible to always return a signed integer of the same size with an
OverflowError on overflow (at least, any floating point that is round-able
without loss of precision will be covered). If `__round__` ends up being
implemented for ndarrays too, I guess the correct behavior will be whatever
we come up for signaling failure in integer operations (see current
behavior of `np.array([0, 1]) // np.array([0, 1])`).
Also note the comment posted by @njsmith on the github issue thread:
I'd be fine with matching python here, but we need to run it by the mailing
list.
Not clear what the right kind of deprecation is... Normally FutureWarning
since there's no error involved, but that would both be very annoying
(basically makes round unusable -- you get this noisy warning even if what
you're doing is round(a).astype(int)), and the change is relatively low
risk compared to most FutureWarning changes, since the actual values
returned are identical before and after the change.
Thoughts?
Antony
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20160413/a470a6d9/attachment.html>
More information about the NumPy-Discussion
mailing list