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

Mark Campanelli mark.campanelli at gmail.com
Tue Dec 12 20:07:53 EST 2017

The different approaches and corresponding "code bloat" here is one of the
most annoying things I have found about using numpy+scipy. Furthermore, the
flip side to the handling of the inputs, including both type and shape, is
getting the output to match the input, including both type and shape.
Getting the output correct is exacerbated by different intermediate
functions not following any standards whatsoever around returning an output
that "matches" the input.

This makes me long for strong typing in Python and even tempts me to port
my production code to something "safe" like Rust (including proper generic
types and concurrency-safety guaranteed by the compiler). I think I saw
some other discussion recently about numpy joining forces with Python 3's
gradual type system. Is there any draft formal proposal for this yet? If
numpy+scipy wants to scale to "bigger" projects, I think it behooves the
community to get rid of this messiness.

On Tue, Dec 12, 2017 at 2:03 PM, Robert Kern <robert.kern at gmail.com> wrote:

> 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
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at python.org
> https://mail.python.org/mailman/listinfo/numpy-discussion
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20171212/1597426d/attachment-0001.html>

More information about the NumPy-Discussion mailing list