문제

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.

다른 팁

Try using np.asarray to convert inputs into arrays instead. It's guaranteed not to copy anything if the input is already a Numpy array. If you expect to receive array subclasses, use np.asanyarray.

Note that a lot of Numpy interfaces don't care if the input is 1- or 2-dimensional -- for example, np.dot works with both 1- and 2-dimensional input. It's probably best to leave it that way -- that way, things like scalar multiplication just work.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top