如何解决Pylance类型检测错误与自定义装饰器的冲突?

如何解决Pylance类型检测错误与自定义装饰器的冲突?

PyLance类型检查与自定义装饰器冲突的解决方法

python开发中,静态类型检查工具(如PyLance)经常会与自定义装饰器产生类型检查错误或警告。本文将通过一个示例,演示如何解决PyLance在自定义装饰器中报告的类型不匹配问题。

问题示例:

以下代码片段展示了一个自定义装饰器execute和被装饰的函数query_data_source:

def execute(func):     def inner_wrapper(*args, **kwargs) -> result[any]: # 问题所在         with Session.begin() as session:             result = session.execute(func(*args, **kwargs))             return result      return inner_wrapper   @execute def query_data_source(     start_id: int = 1, max_results_amount: int = 10 ) -> select:  # PyLance认为此处返回类型为select     stmt = (         select(             datasource.id,             datasource.name,             datasource.source_url,             datasource.author,             datasource.description,             datasource.cover_image_url,             datasource.start_date,             datasource.end_date,         )         .where(datasource.id >= start_id)         .limit(max_results_amount)         .order_by(datasource.id)     )     return stmt

运行时该代码没有问题,但PyLance会警告query_data_source的返回类型不匹配,因为它推断出execute装饰器改变了返回类型为result[any]。

解决方案:

为了解决此问题,我们需要在装饰器定义中添加更精确的类型提示,明确装饰后函数的返回类型。修改后的代码如下:

from typing import Callable, Any  def execute(func: Callable[..., Result]) -> Callable[..., Result]: # 添加类型提示     def inner_wrapper(*args, **kwargs) -> Result[Any]:         with Session.begin() as session:             result = session.execute(func(*args, **kwargs))             return result      return inner_wrapper

通过在execute装饰器中添加Callable[…, Result]类型提示,我们告诉PyLance装饰后的函数返回Result类型。 …表示参数数量和类型不确定,Result假设是自定义类型或已导入的类型。 这解决了PyLance的类型检查错误,并确保类型信息准确无误。

此方法适用于许多自定义装饰器的类型检查问题。 通过添加合适的类型提示,可以有效地与类型检查工具协同工作,提高代码质量和可维护性。 记住根据你的实际情况替换Result和session为你的代码中使用的实际类型和对象

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享