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

时间:2020-09-05 17:55:04

标签: python python-decorators mypy

在使用已安装(通过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]

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

为什么当装饰器代码位于程序包中而不是在应用程序代码中时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]:
    ....

1 个答案:

答案 0 :(得分:0)

结果是我导入的软件包没有正确的元数据,无法让MyPy知道该软件包正在键入。 https://mypy.readthedocs.io/en/stable/installed_packages.html?highlight=py.typed#making-pep-561-compatible-packages 在将py.typed中的package_data添加到setup中之后,对于导入的包,一切正常