[Numpy-discussion] deprecating float(x) for ndim > 0

Nico Schlömer nico.schloemer at gmail.com
Wed Sep 15 08:18:05 EDT 2021


Hi everyone,

This is seeking input on PR [1] which I've worked on with @eric-wieser
and @seberg. It deprecates
```
float(x)
```
if `x` is an array of ndim > 0. (It works with all arrays of size 1
right now.) This aligns the behavior of float() on ndarrays with
float() on lists which already fails today. It also deprecates the
implicit conversion to float in assignment expressions like
```
a = np.array([1, 2, 3])
a[0] = [5]  # deprecated, should be a[0] = 5
```
In general, the PR makes numpy a tad bit stricter on how it treats
scalars vs. single-item arrays.

The change also prevents the #1 wrong usage of float(), namely for
extracting the scalar value from an array. One should rather use
`x[0]` or `x.item()` to that which doesn't convert the value to a
Python float.

To estimate the impact of the PR, I looked at major numpy dependents
like matplotlib, scipy, pandas etc., and of course numpy itself.
Except scipy, all projects were virtually clean to start with. Scipy
needed some changes for all tests to pass without warning, and all of
the changes were improvements. In particular, the deprecation
motivates users to use actual scalars when scalars are needed, e.g.,
in the case of scipy, as the return value of a goal functional.

It'd be great if you could try the branch against your own project and
let us know (here or in the PR) about and problems that you might
have.

Thanks!
Nico

[1] https://github.com/numpy/numpy/pull/10615
[2] https://github.com/numpy/numpy/issues/10404


More information about the NumPy-Discussion mailing list