我想用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等,但我无法使其工作。
你的
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]