Search code examples
pythonvisual-studio-codepylint

Pylint on VS Code with WSL2: Unable to import local packages (import-error)


Context:

  • Windows 10 + VS Code + WSL2
  • WSL2 using Ubuntu 20.04 and all the dev environment is installed inside the distro
  • On the distro I use pyenv to create a virtual environment
  • My workspace has a project with sub-projects folder structure, I need to configure pylint for one specific sub-project
  • I'm using python 3.10 and have already installed pylint in the virtual environment
  • Virtual environment folder is under ~/venvs/virtualenv
  • I've already selected the python interpreter on VS Code pointing to ~/venvs/virtualenv python binary

Folder structure:

main_project/
| .vscode/
| | settings.json <----- B
| sub_projects/
| | proj_1/
| | proj_2/
| | | src/
| | | | app/
| | | | | __init__.py 
| | | | | api/
| | | | | | rest/
| | | | | | | __init__.py <--- A
| | | | | services/
| | | | | | __init__.py
| | | | | | database.py

The problem I have:

  • the code runs without problems, but pylint complains about the following import in A: from app.services import database
  • The error is Unable to import 'app.services' pylint(import-error)

These are my current settings.json file (B on the tree):

{
    "editor.formatOnSaveMode": "file",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "source.organizeImports": true
    },
    "python.formatting.provider": "autopep8",
    "python.linting.pylintEnabled": true,
    "python.linting.enabled": true,
}

Question How should I configure settings.json to make pylint recognize the import? Besides the code running, even the autocomplete is working, which shows that the python interpreter is properly set, so the problem seems to be pylint.


Solution

  • Vscode identification file is found with the workspace as the root directory. You can use the following methods to import method:

    1. Use code from sub_projects.proj_2.src.app.services import database

    2. Place a .env file at the root of your project which adds your source directory to PYTHONPATH:

      PYTHONPATH=/sub_projects/proj_2/src/

    Tips: You can add the following code to your settings.json, you can also change the file name here.

    "python.envFile": "${workspaceFolder}/.env" // for example "python.envFile": "${workspaceFolder}/dev.env"