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

Robert Kern robert.kern at gmail.com
Tue Dec 12 16:03:52 EST 2017


On Wed, Dec 13, 2017 at 5:52 AM, Eric Wieser <wieser.eric+numpy at gmail.com>
wrote:

> Using np.iscalar is a bad idea, as it fails for 0d arrays. x.ndim is the
> better option there.
>
> I’d maybe suggest not special-casing 0d arrays though, and using:
>
> def func_for_scalars_or_vectors(x):
>     x = np.asanyarray(x) # convert scalars to 0d arrays
>
>     # The magic happens here
>
>     return ret[()]  # convert 0d arrays to scalars
>
> Good call. I didn't think that the empty tuple was valid for anything but
indexing into 0d arrays, but of course, following the rules of indexing, it
works as required for other arrays too.

-- 
Robert Kern
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20171213/b00fd723/attachment.html>


More information about the NumPy-Discussion mailing list