当使用已安装(通过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]:
....
结果是,我导入的包没有正确的元数据,无法让MyPy知道包中有类型。 https://mypy.readthedocs.io/en/stable/installed_packages.html?highlight=py.typed#making-pep-561-compatible-packages 在
setup
中将py.typed
添加到package_data
后,所有导入的包都正常工作相关问题 更多 >
编程相关推荐