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

Marten van Kerkwijk m.h.vankerkwijk at gmail.com
Tue Dec 12 21:20:35 EST 2017

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! If you really need, e.g., the shape,
you can do `getattr(input, 'shape', ())` and things may well work for
scalars, and also for objects that behave somewhat like arrays ("duck

If you do go for coercion, I agree with Eric' comment about
`np.asanyarray` - it may now just work for `MaskedArray` (but not for,
e.g., SparseArray; that needs real duck-typing).

All the best,


More information about the NumPy-Discussion mailing list