使用泛型更改输出的 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 强制装饰器方法返回一个函数,该函数采用相同的输入但不同的通用输出

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)