laser3000
laser3000

Reputation: 31

How to type a variable that is passed to numpy.asarray to produce a 2D float array?

I often write functions/methods that take some variable which can come in many forms, i.e., lists of lists, lists of tuples, tuples of tuples, etc. all containing numbers, that I want to convert into a numpy array, kinda like the following:

import numpy as np

def my_func(var: 'what-freaking-type-here') -> np.ndarray:
    a = np.asarray(var, dtype=np.float64) # type: np.array[np.float] maybe?
    return a

Basically my question is how to type this appropriately, given that I can pass all kinds of values to this function to finally create a 2D float array (note that this just an example and the dimensionality and type should be interchangeable):

my_func([[0], [0]])
my_func([(0,), (2.3,)])
my_func(((0,), [2.3,]))
my_func(np.arange(100).reshape(10, 10))

I have this practice of taking all kinds of values and turning them into numpy arrays in a lot of places, to make working with the functions easy and intuitive. However, I have no idea how to properly type this to verify with mypy. Any hints?

Upvotes: 2

Views: 2892

Answers (1)

Jerry101
Jerry101

Reputation: 13457

Try the numpy-stubs: experimental typing stubs for NumPy.

It defines the type of the np.array() function like this:

def array(
    object: object,
    dtype: _DtypeLike = ...,
    copy: bool = ...,
    subok: bool = ...,
    ndmin: int = ...,
) -> ndarray: ...

Which takes any object for the contents and returns an ndarray type.

It's a work in progress. Do report back if it's effective at this stage.

There's also an older project numpy-mypy. As it points out,

Quite a few numpy methods are incredibly flexible and they do their best to accommodate to any possible argument combination. ... Although this is great for users, it caused us a lot of problems when trying to describe the type signature for those methods.

It defines the type of the np.array() function like this:

def array(object: Any, dtype: Any=None, copy: bool=True,
          order: str=None, subok: bool=False,
          ndmin: int=0) -> ndarray[Any]: ...

Which takes Any for the contents (no type checking there) and returns an ndarray type that's parameterized (generic) by the element type.

Upvotes: 1

Related Questions