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

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

解决方案: 利用 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类型检测问题?的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/3169482.html

(0)
上一篇 2025年3月31日 09:20:47
下一篇 2025年3月31日 09:20:55

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论