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

VSCode中如何让类文档字符串内的属性注释在hover时正常显示?

VSCode中如何让类文档字符串内的属性注释在hover时正常显示?

我之前也碰到过完全一样的问题!咱们团队用的这种把属性说明放在类级docstring的Attributes区块里的写法,确实符合很多规范(比如Google风格),但VSCode的Pylance默认有时候不会主动把这些内容关联到对应的属性上,导致hover时看不到注释。

给你几个亲测有效的解决办法:

1. 配置Pylance识别对应docstring风格

Pylance其实是支持解析Google风格的类docstring的,但需要你明确配置:

  • 打开VSCode设置(快捷键Ctrl+,)
  • 搜索python.analysis.docstringFormat
  • 把选项改成google
  • 重启VSCode或者通过Ctrl+Shift+P执行「Python: Restart Language Server」

这样设置后,Pylance就会自动解析类docstring里的Attributes区块,hover属性时就能看到对应的注释了。

2. 使用Annotated类型提示(推荐)

如果不想改全局设置,或者想更稳妥地让属性注释被识别,可以用typing.Annotated把类型和注释绑定在一起,写法如下:

from dataclasses import dataclass
from typing import Annotated

@dataclass
class SessionMetadata:
    """Metadata of a Session"""
    created_at: Annotated[int, "Date of creation, in POSIX timestamp format."]
    usage_count: Annotated[int, "The number of times the session was applied to the payload."]

这种写法不仅Pylance能完美识别,其他Python语言服务(比如Pyright)也能支持,hover时注释会直接显示出来。

3. 折中的双重注释法

如果要严格保留团队的类docstring规范,同时保证hover能看到注释,可以给属性加个简短的行内注释,虽然有点重复,但简单有效:

@dataclass
class SessionMetadata:
    """Metadata of a Session
    Attributes:
        created_at: Date of creation, in POSIX timestamp format.
        usage_count: The number of times the session was applied to the payload.
    """
    created_at: int  # Date of creation, in POSIX timestamp format.
    usage_count: int  # The number of times the session was applied to the payload.

另外提一句,有时候Pylance的缓存会抽风,就算设置对了也不生效,这时候重启语言服务基本就能解决问题。

备注:内容来源于stack exchange,提问作者Camille Louédoc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 15:48:03