Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the number of values in a tuple type hint be parameterized?

Take the following code snippet (written for no purpose other than to show the type hint):

import numpy as np

def func() -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    arr1 = np.empty(shape=(5,))
    arr2 = np.ones(shape=(5,))
    arr3 = np.zeros(shape=(5,))
    return arr1, arr2, arr3

As the number of return values grow, it becomes tedious to write out each "np.ndarray" by hand. Is there a way to type hint the number of np.ndarrays without typing them out individually?

What I mean is something like this (nonfunctional) code:

import numpy as np

def func() -> tuple[*([np.ndarray]*3)]:
    arr1 = np.empty(shape=(5,))
    arr2 = np.ones(shape=(5,))
    arr3 = np.zeros(shape=(5,))
    return arr1, arr2, arr3
like image 909
Rocajoy Avatar asked Oct 15 '25 16:10

Rocajoy


1 Answers

If you're willing to type it as a tuple containing any number of np.ndarray types, you can use tuple[np.ndarray,...]. Otherwise, you need to specify the types individually.

If you go with the specific number of np.ndarray elements, you can save typing by creating a type alias:

TupleOf3NDArrays = tuple[np.ndarray,np.ndarray,np.ndarray]

def func() -> TupleOf3NDArrays:
    ...
like image 149
J Earls Avatar answered Oct 18 '25 10:10

J Earls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!