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

Stephan Hoyer shoyer at gmail.com
Wed Sep 15 13:41:34 EDT 2021


On Wed, Sep 15, 2021 at 5:18 AM Nico Schlömer <nico.schloemer at gmail.com>
wrote:

> 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.
>

Hi Nico,

I think this is a great idea! Another good alternative to mention is
explicitly calling .squeeze() first, to remove all size 1 dimensions.

Cheers,
Stephan


> 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
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at python.org
> https://mail.python.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/numpy-discussion/attachments/20210915/7b52327e/attachment.html>


More information about the NumPy-Discussion mailing list