[Numpy-discussion] What is the pythonic way to write a function that handles arrays and scalars?

Stephan Hoyer shoyer at gmail.com
Wed Dec 13 01:19:48 EST 2017

On Tue, Dec 12, 2017 at 6:20 PM Marten van Kerkwijk <
m.h.vankerkwijk at 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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20171213/4febacc5/attachment.html>

More information about the NumPy-Discussion mailing list