MyPy无法识别修饰函数的返回类型

2024-10-03 02:45:50 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用已安装(通过pip install)包中的装饰程序时,我遇到了一个奇怪的mypy故障。 在我的应用程序代码中编写的同一个装饰器工作得很好

我有这样一个函数:

def _subscription_entity(self) -> Optional[SubscriptionEntity]:
   return get_subscription(...)  # get_subscription() is a decorated function

MyPy失败,出现错误:Returning Any from function declared to return Optional[SubscriptionEntity]

但是,如果我复制整个decorator代码,并将其放在我的应用程序代码中(在一个单独的文件中,并导入该文件,而不是包安装的文件),所有工作都会按预期进行。没有错误。我还测试了更改_subscription_entity签名以返回int,得到了预期的错误Returning Optional[SubscriptionEntity] from function declared to return int

为什么当decorator代码存在于包中而不是应用程序代码中时,mypy会失败

简化的装饰器如下所示

F = TypeVar('F', bound=Callable[..., Any])

def test_cache(wrapped_func: F) -> F:

    @wraps(wrapped_func)
    def decorated_func(*args: Any, **kwargs: Any)-> F:
        return _handle(wrapped_func, *args, **kwargs)

    return cast(F, decorated_func)

def _handle( wrapped_func: Callable, *args: Any, **kwargs: Any) -> F:
    return wrapped_func(*args, **kwargs)

装饰功能是:

@test_cache
def get_subscription(cls, request: GetSubscriptionRequest) -> Optional[SubscriptionEntity]:
    ....

Tags: getreturndefargsanyfunction装饰optional