如何根据方法输入推断Python类泛型?

问题描述 投票:0回答:1

我想用Python写一个像这样的管道:

from collections.abc import Callable
from typing import Generic, TypeVar

T = TypeVar("T")
U = TypeVar("U")
V = TypeVar("V")


class Pipeline(Generic[T, U]):
    def pipe(self, _cb: Callable[[U], V]) -> "Pipeline[T, V]":
        ...


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


a = Pipeline()
a = a.pipe(int_to_str)
     # the inferred type is Pipeline[Unknown, str]
     # I would like it to be Pipeline[int, str]

无论如何,python 可以理解,因为传递的第一个函数是一个将 int 作为 inout 的函数,那么管道第一个泛型类型应该是 int 吗?

我尝试使用@overload等,但我无法使其工作。

python type-hinting typing
1个回答
0
投票

你的

pipe
功能没有问题。 您没有正确输入
a

在您的示例中,您有:

a = Pipeline()
# type of a: Pipeline[Unknown, Unknown]`
# doing pipe(int_to_str) replaces the second argument correctly with `str`

现在应该像这样工作:

from collections.abc import Callable
from typing import Generic, TypeVar

T = TypeVar("T")
U = TypeVar("U")
V = TypeVar("V")


class Pipeline(Generic[T, U]):
    def pipe(self, _cb: Callable[[U], V]) -> "Pipeline[T, V]":
        ...


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


a: Pipeline[int, int] = Pipeline()
b = a.pipe(int_to_str)
     # the inferred type is Pipeline[int, str]
© www.soinside.com 2019 - 2024. All rights reserved.