VSCode中Pylance对Python类方法类型注解报错求助
解决Pylance对classmethod类型注解报错的问题
问题说明
VSCode 1.83.0搭配Pylance v2023.10.20时,所有类的classmethod类型注解都会触发错误警告。示例代码如下:
from __future__ import annotations class A: @classmethod def foo(cls: type[A]) -> str: return "bar"
Pylance给出的报错信息:
Argument of type "(cls: type[A]) -> str" cannot be assigned to parameter "__f" of type "() -> _R_co@classmethod" in function "__init__" Type "(cls: type[A]) -> str" cannot be assigned to type "() -> _R_co@classmethod"PylancereportGeneralTypeIssues
当前VSCode的settings.json配置:
{ "editor.formatOnSave": true, "editor.rulers": [140], "flake8.args": ["--config=setup.cfg"], "flake8.path": ["${workspaceFolder}/venv/bin/python", "-m", "flake8"], "[python]": { "editor.defaultFormatter": "ms-python.black-formatter", "editor.formatOnSave": true }, "black-formatter.args": ["--line-length", "120"], "mypy-type-checker.args": ["--config-file=setup.cfg"], "mypy-type-checker.path": [ "${workspaceFolder}/venv/bin/python", "-m", "mypy" ], "python.languageServer": "Pylance", "python.analysis.typeCheckingMode": "basic", "files.exclude": { "**/.git": true, "**/.svn": true, "**/.hg": true, "**/CVS": true, "**/.DS_Store": true, "**/Thumbs.db": true, "**/__pycache__": true, "**/.pytest_cache": true, "**/.mypy_cache": true, "**/venv": true }, "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python", "autoDocstring.docstringFormat": "google-notypes" }
setup.cfg配置:
[flake8] max-line-length = 120 extend-ignore = # no whitespace before colon on list slice E203, # line break occurred before a binary operator W503, # comparison to True should be is not == (not true for pandas) E712, # line too long (handled by formatter automatically whenever possible) E501, # missing type annotation for self in method ANN101, # missing type annotation for *args, **kwargs ANN002, ANN003 per-file-ignores = # imported but unused __init__.py: F401 exclude = .vscode, .git, __pycache__, venv, tests require-plugins = flake8-annotations, flake8-pep585 # infer no return as a None return type suppress-none-returning = true # for mypy mypy-init-return = true # allow importing from typing for convenience pep585-whitelisted-symbols = Iterator Iterable Callable [mypy] exclude = .vscode, .git, __pycache__, venv, tests strict_optional = False
解决方案
1. 升级Pylance版本
你用的Pylance v2023.10.20存在classmethod类型注解的兼容性bug,后续版本已经修复了这个问题。直接在VSCode扩展市场搜索Pylance,点击更新到最新版本即可解决。
2. 调整类型注解写法(兼容旧版本)
如果暂时无法升级,可修改cls的类型注解为Type[A](需要从typing导入),或者直接省略cls的类型注解(Pylance会自动推断类型):
# 写法1:导入Type from __future__ import annotations from typing import Type class A: @classmethod def foo(cls: Type[A]) -> str: return "bar" # 写法2:省略cls的类型注解 from __future__ import annotations class A: @classmethod def foo(cls) -> str: return "bar"
3. 临时禁用该类型检查规则
如果需要快速屏蔽报错,可在VSCode的settings.json中添加以下配置:
"python.analysis.diagnosticSeverityOverrides": { "reportGeneralTypeIssues": "none" }
注意:这个方法会禁用所有reportGeneralTypeIssues类的警告,建议优先使用前两种方案。
内容的提问来源于stack exchange,提问作者Avinash Raj
相关产品推荐
相关产品推荐

