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
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:
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With