
如何解决使用自定义装饰器时 pylance 类型检测错误?
python 代码使用自定义装饰器来包装函数,使其在运行时执行特定的操作。然而,pylance 类型检查器有时无法识别装饰函数的返回类型,从而导致错误。
以下示例说明了这种错误:
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: # 忽略
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 函数被装饰了 execute 装饰器。pylance 导致类型错误,假设 query_data_source 返回 select 而不是装饰函数声明的 result[any]。
立即学习“Python免费学习笔记(深入)”;
为了解决此问题,可以修改装饰器以显式指定函数返回类型:
from typing import Callable def execute(func) -> Callable[..., Result]:
通过指定返回类型注释,pylance 将能够正确推断装饰函数的返回类型并消除错误警告。
以上就是Python自定义装饰器导致Pylance类型检测错误如何解决?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号