Pylance类型检测报错:如何解决自定义装饰器导致的类型错误?

ID:21535 / 打印

pylance类型检测报错:如何解决自定义装饰器导致的类型错误?

解决使用自定义装饰器时的 pylance 类型检测错误

使用自定义装饰器时,pylance 可能会报告类型检测错误,即使实际代码运行正常。这通常是由于 pylance 无法正确识别自定义装饰器的返回类型。

考虑以下示例代码:

from typing import callable  def execute(func) -> callable[..., result]:     def inner_wrapper(*args, **kwargs):         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

此代码的一个问题是 pylance 假设 query_data_source 函数返回 select 对象,而不是 result 对象。为了解决此错误,修改 execute 装饰器以明确声明其返回类型的返回类型:

def execute(func) -> Callable[..., Result]:

此修改通知 pylance execute 装饰的函数返回 result 对象,从而消除类型检测错误。

上一篇: 如何用Python统计分类列数据在不同日期的出现次数?
下一篇: Python正则表达式非贪婪匹配结果减少的原因是什么?

作者:admin @ 24资源网   2025-01-14

本站所有软件、源码、文章均有网友提供,如有侵权联系308410122@qq.com

与本文相关文章

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。