I am learning Python and numpy, and am new to the idea of duck typing. I’m writing functions into which something/someone should pass a numpy array. Trying to embrace duck typing, I’m writing my 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…
So to take care of 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() is likely to throw. Thus I currently just have this:
# 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 try to catch here? Thanks.
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.