[Python] Collecting return types from vararg Callable for use elsewhere in signature?

Discussão em 'Python' iniciado por Stack, Julho 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following function signature:

    Y = Annotated[TypeVar("Y"), "That which might be yielded"]
    R = Annotated[TypeVar("R"), "That which might be returned"]

    def teeinto_constantmemory(
    it: Iterable[Y],
    *consumer_callables: Callable[[Iterable[Y]], R]
    ) -> Tuple[R, ...]: ...


    This function signature is obviously inadequate.


    1. It doesn't indicate that the length of the return value is equal to the quantity of consumer_callables.


    2. Further, it doesn't indicate that the n-th element of the return tuple has the same type as the return type of the n-th element of consumer_callables (especially when the callables return different types from each other).

    I already checked out PEP 646, but the closest section they had to relevant was “Type Variable Tuples with Callable”, which I couldn't see how to apply to this situation.

    Have I missed the solution, or is this use-case actually not yet addressed by Python's type hinting ecosystem?


    For example, if you call the function with five positional arguments, of types


    1. Iterable


    2. Callable[[Iterable], int]


    3. Callable[[Iterable], float]


    4. Callable[[Iterable], str]


    5. Callable[[Iterable], FooType]

    then the return value will be of type

    • Tuple[int, float, str, FooType]

    Continue reading...

Compartilhe esta Página