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

Pyright误将CreateKeyRingRequest的parent属性识别为Field而非str类型

Pyright误识别Google Proto消息属性类型的问题与解决

问题详情

Pyright(不管是Vim里的coc-pyright还是VSCode的Pylance)把CreateKeyRingRequest的parent属性认错了——明明官方文档标注这是str类型,它偏识别成Field类型,导致赋值时直接报错。

这个CreateKeyRingRequest继承自谷歌proto.message.Message类,官方文档对parent的定义明确:

|  Attributes:
 |      parent (str):
 |          Required. The resource name of the location associated with
 |          the [KeyRings][google.cloud.kms.v1.KeyRing], in the format
 |          ``projects/*/locations/*``.

环境版本

  • coc.nvim + coc-pyright 1.1.262(配套Pyright 1.1.263)
  • NVIM v0.8.0-dev+3-g3f2e9298b

触发代码

from google.cloud import kms_v1
request = kms_v1.CreateKeyRingRequest()
request.parent = "test"

报错信息

[PyRight reportGeneralTypeIssues]
Cannot assign member "parent" for type "CreateKeyRingRequest"
Expression of type "Literal['test']" cannot be assigned to member "parent"...
"Literal['test']" is incompatible with type Field

解决办法

1. 更新依赖包

大概率是google-cloud-kms的类型注解文件存在问题,先尝试更新到最新版本:

pip install --upgrade google-cloud-kms

更新后重启编辑器,检查类型识别是否恢复正常。

2. 用构造函数初始化代替直接赋值

避免直接给属性赋值,创建实例时直接传入参数,Pyright通常能正确识别这种写法的类型:

request = kms_v1.CreateKeyRingRequest(parent="test")

3. 临时绕过类型检查

如果更新后问题仍存在,可临时通过注释忽略类型错误:

request.parent = "test"  # type: ignore

或者用类型断言强制指定类型:

from typing import cast
request.parent = cast(str, "test")

4. 降级Pyright版本

若为新版本Pyright引入的兼容性问题,可降级到之前稳定的版本。比如在coc-settings.json中指定版本:

"pyright.version": "1.1.259"

执行:CocRestart重启coc服务即可生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 02:45:34