Setting Python source folders in Visual Studio Code

Visual Studio Code is my preferred editor. Unfortunately, it doesn’t work with additional Python source folders out of the box. This blog shows how to add a Python source folder and regain the developer experience you’ve come to love.

Although it’s common to use top-level modules, Python allows you to organize your project any way you want. The src-based module layout uses a src-folder to store the top-level modules.

Basic module layoutSrc-based module layout
/project/module.py/project/src/module.py
/project/tests/test_module.py/project/tests/test_module.py
/project/requirements.txt/project/requirements.txt

To configure Python to search for modules in the src-folder we alter the default search path. In PyCharm this is done by selecting a source folder. In Visual Studio Code, this is done by setting the PYTHONPATH variable.

Add source folder to PYTHONPATH

Modify settings.json to include the source folder “src” in the integrated terminal:

{
    "terminal.integrated.env.osx": {
        "PYTHONPATH": "${workspaceFolder}/src",
    },
    "terminal.integrated.env.linux": {
        "PYTHONPATH": "${workspaceFolder}/src",
    },
    "terminal.integrated.env.windows": {
        "PYTHONPATH": "${workspaceFolder}/src",
    },
    "python.envFile": "${workspaceFolder}/.env"
}

And add or modify .env to include the source folder “src” in the editors’ Python environment:

PYTHONPATH=./src

Note that the PYTHONPATH must be set for both the editors’ Python environment and the integrated terminal. The editors’ Python environment is used by extensions and provides linting and testing functionality. The integrated terminal is used when debugging to activate a new python environment.

Remark This configuration overwrites the existing PYTHONPATH. To extend, use the following settings:

{
    "terminal.integrated.env.osx": {
        "PYTHONPATH": "${env:PYTHONPATH}:${workspaceFolder}/src",
    },
    "terminal.integrated.env.linux": {
        "PYTHONPATH": "${env:PYTHONPATH}:${workspaceFolder}/src",
    },
    "terminal.integrated.env.windows": {
        "PYTHONPATH": "${env:PYTHONPATH};${workspaceFolder}/src",
    }
}
PYTHONPATH=${PYTHONPATH}:./src # Use path separator ';' on Windows.

Resume development

There is no need to reload the workspace. Just open any Python file and enjoy the editors’ capabilities. Please note that it’s safe to include the settings.json file in source control.

If you dislike this additional configuration, feel free to restructure your project. Using the top-level module structure or by creating packages.

Share this article: Tweet this post / Post on LinkedIn