0

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

2 Answers 2

2

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
    . . .

0
0

What about following?

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


def fill_with_ones(array: NDArray[Shape["*, *"], Int32) -> NoReturn:
    ...

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.