Search code examples
pythonnumpyduck-typing

numpy.array() exceptions thrown


I am new to Python, numpy, and duck typing. I'm writing functions which take a numpy array. To embrace duck typing, I'm writing code to use numpy.array with the copy= and ndmin= options to convert array_likes or 1d/0d arrays into the shape I need. Specifically, I use the ndmin= option in cases where I can accept either a (p,p) array or a scalar; the scalar can be coded as an int, (1,) array, (1,1) array, [1] list, etc...

To handle this, I'm using something like S = numpy.array(S,copy=False,ndmin=2) to get an array (if possible) with the right ndim, then test for the shape as I need. I know I should embed this in a Try-Except block, but can't find any documentation about what kind of exception numpy.array() likely throws. I currently just have:

# duck covariance matrix into a 2d matrix
try:
    S = numpy.array(S, ndmin = 2, copy=False)
except Exception as e:
    raise e

What specific exception(s) should I catch?


Solution

  • Document your function as accepting an array_like object and leave handling of exceptions to a caller.

    numpy.array() is very permissive function it will convert to an array almost anything.