[Python] How can I tell Python that the result type of a pipeline is a certain type?

Discussão em 'Python' iniciado por Stack, Fevereiro 11, 2025.

  1. Stack

    Stack Membro Participativo

    I have a pipeline class based on the reduce function. I was factoring the code today to be able to trace type information and noticed that the reduce function removes the type information so I cannot trace the type. See below code:

    from functools import reduce
    from typing import Callable, TypeVar, TypeAlias

    def int_to_str(i: int) -> str:
    return str(i)

    def str_to_float(s: str) -> float:
    return float(s)

    pipes = [int_to_str, str_to_float]

    _S = TypeVar("S")
    _T = TypeVar("T")
    Pipe : TypeAlias = Callable[[_S], _T]

    def reducer(prev: _S, pipe: Pipe) -> _T:
    return pipe(prev)

    initial_arg = 100
    # Pylance shows that the type of what_type is int,
    # because reduce return type annotation(_T@reduce) is same as the type of initial_arg.
    what_type = reduce(reducer, pipes, initial_arg)
    # what_type=100.0 (float value)
    print(f"{what_type=}")
    # type(what_type)=<class 'float'> (float type)
    print(f"{type(what_type)=}")


    The elements in the list as pipes are literal. So I thinked it might be staticly traceable. But the code result and the Pylance report are different. What can I do to avoid this problem?

    Evironment:

    • Python 3.10

    Continue reading...

Compartilhe esta Página