On Tue, Dec 12, 2017 at 6:20 PM Marten van Kerkwijk <
m.h.vankerkw...@gmail.com> wrote:

> The real magic happens when you ducktype, and ensure your function
> works both for arrays and scalars on its own. This is more often
> possible than you might think!


Sadly, this still doesn't work in a type-stable way.

NumPy's ufuncs convert 0-dimensional arrays into scalars. The typing rules
for functions like np.sin() look like:
- scalar or 0d array -> scalar
- 1d or higher dimensional array -> array

I'm not entirely sure, but I suspect this was a practical rather than
principled choice.

NumPy scalars are "duck arrays" of sorts (e.g., with shape and dtype
attributes) which helps to some extent, but the bugs that slip through are
even harder to understand. This wart reminds me of how mixed basic/advanced
indexing reorders sliced dimensions to make the result more "intuitive",
which only works in some cases.

I usually favor coercing all arguments to my functions to numpy arrays with
np.asarray(), but to guarantee the return type you would also need to
coerce it with np.asarray(), too.
_______________________________________________
NumPy-Discussion mailing list
NumPy-Discussion@python.org
https://mail.python.org/mailman/listinfo/numpy-discussion

Reply via email to