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

Discussão em 'Python' iniciado por Stack, Agosto 5, 2025.

  1. Stack

    Stack Membro Participativo

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


    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

    Continue reading...

Compartilhe esta Página