首页 > 解决方案 > 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]:
    ....

标签: pythonpython-decoratorsmypy

解决方案


结果我导入的包没有正确的元数据让 MyPy 知道包有类型。 https://mypy.readthedocs.io/en/stable/installed_pa​​ckages.html?highlight=py.typed#making -pep-561-compatible- packages 添加py.typed到所有工作正常package_datasetup导入包


推荐阅读