Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make pylint in VSCode know that it's in a package (so that relative imports work)?

Layout:

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 and pylint error:

from .foo import harr
   ^

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

The program runs fine if not for the linter error. I have tried modifying sys.path in __init__.py and through pylintrc but the result is the same.

Is there a way VSCode can run linting for a file and know at the same time that the file is part of a package?

I've scanned through vscode linting and the pylint config docs but found nothing like what I'd expect. This should be so standard, what am I not getting? How is pylint supposed to work out relative imports if it has no idea of the top-level package?

like image 868
MatrixTheatrics Avatar asked Aug 12 '20 09:08

MatrixTheatrics


1 Answers

Currently pylint cannot find modules accurately through relative imports, it will mess up the path, although the code can run.

You could try the following two ways to solve it:

1.Add the following settings in the setting.json file.

"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", 
  ],

(Since there is no issue with the code, we can turn off this type of pylint prompt.)

  1. Since the relative import method will make pylint confusing, we can avoid such use.

    Use 'from foo import harr' instead of 'from .foo import harr'.

Reference: Default Pylint rules.

like image 59
Jill Cheng Avatar answered Sep 29 '22 06:09

Jill Cheng