Suggestion: prevent silent downcast in np.full_like
![](https://secure.gravatar.com/avatar/826500d3bab212c5bc3f7b932bece55f.jpg?s=120&d=mm&r=g)
Hello, This is my first activity on this mailing list, please let me know if I am doing anything improperly. I recently opened issue #15635 <https://github.com/numpy/numpy/issues/15635>and it was suggested to me that it could be worth discussing here. 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 This is consistent with the documentation (which even gives an example of this unsafe casting), and was obvious to fix once identified. But what seems especially problematic to me is the fact that the code /looks safe, but isn't/. There is no sketchy `dtype=...` to make you think twice about the possibility of downcasting, but it happens all the same. What are your thoughts on this topic? Should a special warning be given? Should the casting rule be made more strict? Alexis THIBAULT
![](https://secure.gravatar.com/avatar/d9ac9213ada4a807322f99081296784b.jpg?s=120&d=mm&r=g)
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
participants (2)
-
A T
-
Stefan van der Walt