How to use numpy in optional typing

16,743

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.

Share:
16,743
Michelrandahl
Author by

Michelrandahl

Works with Clojure. Plays with F#, Idris, Prolog, Elixir, Python and C. Passionate about functional programming, and especially interested in dependently typed languages.

Updated on June 16, 2022

Comments

  • Michelrandahl
    Michelrandahl almost 2 years

    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>.
    
  • Michelrandahl
    Michelrandahl over 8 years
    Thank you. I have recently resolved to using the built-in type(...) function to print the exact types of variables I am in doubt about.. Sometimes it requires a bit detective work when using libraries such as matplotlib, but at least it has helped me finding types so far so I can put them in my function declarations.