[Numpy-discussion] What is the pythonic way to write a function that handles arrays and scalars?
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>
> 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.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion