[Numpy-discussion] Suggestion: prevent silent downcast in np.full_like

Stefan van der Walt stefanv at berkeley.edu
Mon Feb 24 18:03:34 EST 2020


Hi Alexis,

On Mon, Feb 24, 2020, at 12:00, A T wrote:
> Here is a summarized code example of how unsafe downcasting in np.full_like() resulted in issues in our scientific toolbox:
> 
>  t0 = 20.5
> # We're trying to make a constant-valued "ufunc"
> temperature = lambda x: np.full_like(x, t0)
> print(temperature([0.1, 0.7, 2.3]))
>  # [20.5 20.5 20.5]
> print(temperature(0))
>  # 20

I agree that this behavior is counter-intuitive. When t0 is not of the same type as x, the user intent is likely to store t0 as-is.

If a check is introduced, there is the question of how strict that check should be. Checking that dtypes are identical may be too strict (there are objects that cast to one another without loss of information). Perhaps, for now, a warning is the best way to flag that something is going on. Users who do not wish to see such a warning can first cast t0 to the correct dtype:

 np.full_like(x, x.dtype.type(t0))

or

 np.full_like(x, int(t0))

I imagine we'd want to show the warning even if dtype is specified.

Best regards,
Stéfan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20200224/cf405e0b/attachment-0001.html>


More information about the NumPy-Discussion mailing list