python - 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]:
....
解决方案
结果我导入的包没有正确的元数据让 MyPy 知道包有类型。
https://mypy.readthedocs.io/en/stable/installed_packages.html?highlight=py.typed#making -pep-561-compatible-
packages 添加py.typed
到所有工作正常package_data
后setup
导入包
推荐阅读
- python-3.x - 熊猫总计数高于阈值
- typescript - TypeScript 动态导入
- c - Getopt 没有在 C 中抓取和存储我的输入
- c# - 我应该为 64 位 Windows 操作系统构建 x86 或 x64 应用程序吗?
- android - 片段切换 - 无法从后台堆栈返回
- javascript - 我应该将什么值传递给 Sanctuary.either()?
- iterator - 有没有办法删除迭代器链中项目的展开,该迭代器链根据结果进行过滤和分区?
- ruby-on-rails - 无法让 Rails API 显示“显示”记录
- php - 隐藏 URL 段但想在 PHP Codeigniter 的控制器方法中访问这些段
- html - 如何使用 CSS 创建一个带有渐变颜色的 3D 长方体