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

如何解决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  @execute def 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 类型,引发类型警告。

立即学习Python免费学习笔记(深入)”;

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

修改后的代码:

from typing import Callable, Any  def 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  @execute def 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 在处理自定义装饰器时对返回类型推断的局限性,从而提高代码的可读性和可维护性。

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