如何使VSCode中的pylint知道它在包装中以便相对导入起作用?

问题描述

布局:

workspace/
  .vscode/launch.json
  main.py
  foo.py:
    def harr(): pass

launch.json:

{
    "version": "0.2.0","configurations": [
        {
            "name": "Python: Module","type": "python","request": "launch","cwd": "${workspaceFolder}/..","module": "${workspaceFolderBasename}"
        }
    ]
}

main.py和pylint错误:

from .foo import harr
   ^

Attempted relative import beyond top-level package - pylint(relative-beyond-top-level)

如果不是因为linter错误,程序运行正常。我尝试通过__init__.py并通过pylintrc修改sys.path,但结果是相同的。

VSCode是否可以为文件运行linting并同时知道该文件是软件包的一部分?

我已经扫描了vscode linting和pylint配置文档,但没有发现与我期望的一样的东西。这应该是标准的,我没有得到什么?如果pylint不了解顶级软件包,应该如何计算相对进口?

解决方法

今天早上早些时候我遇到了同样的问题。

事实证明,您可以在根路径中添加 init .py 文件。

workspace/
    .vscode/launch.json
    __init__.py
    main.py
    foo.py
,

当前pylint无法通过相对导入准确地找到模块,尽管代码可以运行,但会弄乱路径。

您可以尝试以下两种方法来解决它:

1。在setting.json文件中添加以下设置。

"python.linting.pylintArgs": 
  ["--disable=all","--enable=F,E,unreachable,duplicate-key,unnecessary-semicolon,global-variable-not-assigned,unused-variable,binary-op-exception,bad-format-string,anomalous-backslash-in-string,bad-open-mode","--disable=E0402",],

(由于代码没有问题,我们可以关闭这种类型的pylint提示。)

  1. 由于相对的导入方法会使pylint造成混淆,因此我们可以避免这种用法。

    使用'from foo import harr'代替'from .foo import harr'。

参考:Default Pylint rules

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...