You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python上下文管理器Protocol的__enter__返回值类型提示识别异常求助

问题结论:这是代码类型注解精度不足导致的,不是编辑器bug

具体原因

当你直接使用with SqliteContext(self.model) as cursor时,类型检查器能直接读取SqliteContext类中__enter__方法的明确返回类型(即实现了CursorProtocol的游标类),所以类型提示正常。

但如果SqlQueryBuilder中self.context_manager的类型标注仅笼统定义为ContextManagerProtocol,且该协议未明确指定__enter__方法的返回类型为CursorProtocol,类型检查器就无法推断出cursor的具体类型,自然不会显示对应的类型提示。

修复方案

  1. 完善Protocol定义,给ContextManagerProtocol的__enter__方法明确标注返回类型:
from typing import Protocol

class CursorProtocol(Protocol):
    # 定义游标必须实现的方法
    def execute(self, sql: str, params: tuple | None = None) -> None: ...
    def fetchone(self) -> tuple | None: ...

class ContextManagerProtocol(Protocol):
    def __init__(self, model: type) -> None: ...
    # 明确__enter__返回符合CursorProtocol的对象
    def __enter__(self) -> CursorProtocol: ...
    def __exit__(self, exc_type, exc_val, exc_tb) -> None: ...
  1. 修正SqlQueryBuilder的类型标注,确保context_manager的类型是Type[ContextManagerProtocol](因为它是需要实例化的类):
from typing import Type

class SqlQueryBuilder:
    def __init__(self, context_manager: Type[ContextManagerProtocol]) -> None:
        self.context_manager = context_manager

完成以上调整后,类型检查器就能准确识别cursor的CursorProtocol类型,编辑器的类型提示也会正常生效。

内容的提问来源于stack exchange,提问作者Jonathan Voss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 03:12:59