How do I write a 2D-array parameter specification in python

Question:

Context

I’m not used to parameter specifications when declaring a function in python.

In the following example, we specify the parameters x and y to be of type int:

def add(x: int, y: int) -> int:
    return x + y

I’m using numpy to initialize a 2D array of 0s and I’m not sure how to specify a 2D array as my parameter. Here’s what I have:

import numpy as np

def fillWithOnes(array: type([[]])) -> None:
    for row in array:
        for i in range(0, len(row)):
            row[i] = 1

table = np.zeros((5,5))

fillWithOnes(table)

print (table)

Question

Is type([[]]) on line 3 correct? I’ve been having trouble finding an answer in python’s Typing docs here.

I also noticed that I can specify the parameter, array to be an int and the code still works. Which leads me to my second question: Is typing purely for third party tools; maybe general sanity and readability as well?

Thanks

Asked By: Parm

||

Answers:

np.zeros returns a ndarray:

>>> type(np.zeros((5,5)))
<class 'numpy.ndarray'>

So that’s what you’d annotate it as:

def fillWithOnes(array: np.ndarray) -> None:
    . . .

If you wanted to be general though, you could annotate it as a Protocol/base class to allow for multiple different types. You currently only need an "iterable of sequences of ints", so you can specify that:

from typing import Sequence, Iterable

def fillWithOnes(array: Iterable[Sequence[int]]) -> None:
    pass

Now it can accepts lists, ndarrays, and even types you define.


I’ll just mention, for lists, type([[]]) works, slightly. It disregards the inner type of the list. It would be equivalent to:

def fillWithOnes(array: list) -> None:
    . . .

It specifies that it’s a list, but doesn’t say anything about the element type.

Currently, you need to use a List wrapper:

from typing import List

def fillWithOnes(array: List[List[int]]) -> None:  # I'm assuming the cells are ints
    . . .

Answered By: Carcigenicate

What about following?

from typeing import (NoReturn)
from nptyping import (NDArray, Shape, Int32)


def fill_with_ones(array: NDArray[Shape["*, *"], Int32) -> NoReturn:
    ...
Answered By: soumeng78
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.