使用泛型更改输出的 MyPy 装饰器

时间:2021-04-21 04:43:18

标签: python mypy

我正在尝试在 python 中编写一个装饰器,它允许任何输入,但更改 MyPy 强制执行的输出。这是我得到的最接近的:

Output = TypeVar('Output', bound=pydantic.BaseModel)

class Spec(Generic[Output]):
    # implementation

def my_decorator(f: Callable[..., Spec[Output]]) -> Callable[..., Output]:
    # implementation

这让我们定义一个方法:

@my_decorator
def my_method(arg1: str, arg2: int) -> Spec[SomeType]:
    # Implementation

MyPy 然后让我调用这个方法,它期望 SomeType 作为输出而不是 Spec[SomeType]。太棒了!我缺少的部分是如何让它仍然期望相同的输入参数(最好是任何参数,包括无参数)。

我也知道,如果我保持输出相同,我可以为函数定义一个 TypeVar 像这样保持输入常量:

FuncT = TypeVar('FuncT', bound=Callable[..., Any])
def other_decorator(f: FuncT) -> FuncT:
    # implementation

如何让 MyPy 强制装饰器方法返回一个函数,该函数采用相同的输入但不同的通用输出?

0 个答案:

没有答案
相关问题