Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use numpy in optional typing

Lets say I want to make a function which takes a lambda function (Callable) as parameter where the lambda function takes a vector as input (defined as numpy array or numpy matrix) and returns a new vector. How do I declare the type signature for the Callable with numpy types?

My initial attempt looks something like this:

def some_func(calc_new_vector: Callable[[np.array], np.array], ...other-params...) -> SomeType:     ...do stuff...     ...return... 

However, this results in an error when running the interpreter:

TypeError: Callable[[arg, ...], result]: each arg must be a type. Got <built-in function array>. 
like image 484
Michelrandahl Avatar asked Feb 10 '16 23:02

Michelrandahl


People also ask

What is NumPy Arraylike?

ndarray] In the numpy glossary https://numpy.org/doc/stable/glossary.html?highlight=array_like, numpy defines array_like as: Any scalar or sequence that can be interpreted as an ndarray. In addition to ndarrays and scalars this category includes lists (possibly nested and with different element types) and tuples.


1 Answers

Confusingly, np.array is a function useful for creating numpy arrays. It isn't the actual type of the arrays created.

The type is np.ndarray.

So, replace np.array with np.ndarray. That should fix the problem.

like image 62
shx2 Avatar answered Sep 21 '22 07:09

shx2