本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

如何解决Python中自定义装饰器的Pylance类型检测问题?

网络教程 app 1℃

如何解决Python中自定义装饰器的Pylance类型检测问题

Pylance与Python自定义装饰器类型提示的冲突及解决方案

Python装饰器是强大的代码复用工具,但使用自定义装饰器时,静态类型检查器(如Pylance)可能会出现类型提示错误,尤其当装饰器修改了函数的返回类型。本文将演示一个常见问题及解决方案。

问题: Pylance无法正确识别经过自定义装饰器修饰后的函数返回类型。例如,一个装饰器修改了函数的返回类型,但Pylance仍然显示原始函数的返回类型,导致类型警告。

示例代码:

def execute(func): def inner_wrapper(*args, **kwargs) -> result[any]: # Pylance问题所在 with session.begin() as session:result = session.execute(func(*args, **kwargs))return result return inner_wrapper@executedef query_data_source(start_id: int = 1, max_results_amount: int = 10) -> 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

query_data_source 函数实际返回 result[any] 类型,但Pylance 仍然将其识别为 select 类型,引发类型警告。

解决方案: 利用 typing.Callable 更精确地声明装饰器的返回类型,从而帮助Pylance 正确理解装饰器的行为。

修改后的代码:

from typing import Callable, Anydef execute(func: Callable[…, Any]) -> Callable[…, Result[Any]]: # 使用typing.Callable def inner_wrapper(*args, **kwargs) -> Result[Any]: with Session.begin() as session:result = session.execute(func(*args, **kwargs))return result return inner_wrapper@executedef query_data_source(start_id: int = 1, max_results_amount: int = 10) -> 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

通过在 execute 装饰器中使用 Callable[…, Result[Any]] 作为返回类型提示,Pylance 可以准确推断出 query_data_source 函数的实际返回类型,从而消除类型警告。 … 表示参数个数可变,Any 表示参数类型可变。 确保 Result 和 select 类型已正确定义。

此方法有效地解决了 Pylance 在处理自定义装饰器时对返回类型推断的局限性,从而提高代码的可读性和可维护性。

以上就是如何解决Python中自定义装饰器的Pylance类型检测问题?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » 如何解决Python中自定义装饰器的Pylance类型检测问题?

喜欢 (0)