Search code examples
pythonvisual-studio-codevscode-debuggervscode-remote

code navigation within python module not possible in visual studio code


first of all, this is my workspace structure:

workspace_root
├── ...
├── libs
│   └── module_name
│       ├── README.md
│       ├── module_name
│       │   ├── __init__.py
│       │   ├── caller_with_main_calls_service.py
│       │   ├── independent.py
│       │   └── service_calls_indendent.py
│       └── setup.py
├── ...

my issue?

In VSCode, I can't navigate within a module's elements definition. That includes jumping from the import statement straight to the definition of it. I even couldn't start or debug the python main within caller_with_main_calls_service.py, because it said module not found. When installing the module via pip, it works. However, that's not desired during development...

What I tried so far:

  • tried .env approach and set PYTHONPATH to my interpreter + ${workspaceRoot}+"/libs/module_name/module_name"

  • set the workspace settings / settings.json like this:

{
   "python.linting.pylintEnabled": true,
   "python.linting.enabled": true,
   "python.pythonPath": "/path/to/conda_env/python",
   "python.autoComplete.extraPaths": [
       "${workspaceRoot}/libs/module_name/module_name"
   ],
   "editor.formatOnSave": true
}
  • before starting VSCode, I exported the $PYTHONPATH env var in the same manner as in 1) to include the lib path

What does the python files from the module look like:

# example: caller_with_main_calls_service.py
from module_name import service_calls_indendent as sci

Not sure, if that's relevant, but I am working with WSL.


Solution

  • As commented, it's not enough to put from . import service_calls_independent aka relative imports.

    Additionally, the launch.json needs to be adapted:

        {
          "name": "Python: Module Runner",
          "type": "python",
          "request": "launch",
          "module": "libs.module_name.caller_with_main_calls_service",
          "args": [
                1,
                2,
                3
          ],
          "env": {
            "FOO": "BAR"
          }
        }
    

    The important part is the module, where you specify the file with the main inside - without any file extension.