pythonvisual-studio-codeimportautocompletedependencies

VSCode: Auto import/import suggestions for Python dependencies from external libraries


I'm using VSCode for Python programming. One project heavily relies on an external library and often needs to load modules/classes/etc from that library.

When I type a class that is not yet imported and click on "quick fix" (cmd + . on Mac), VSCode automatically suggests what to import. Unfortunately, these suggestions only involve modules from the currently open project - not from any external dependency.

This means, I always have to figure out how to import the missing class from the external library (which package) and manually add the import myself. This is quite tedious when required frequently.

Is there any way to have VSCode auto suggest and import missing debendencies/classes/etc from external libraries similar to what it does with imports from the open project?

I found the setting python.autoComplete.extraPaths and set it to

"python.autoComplete.extraPaths": [  
   "/opt/homebrew/Caskroom/miniforge/base/envs/myenv/lib/python3.8/site-packages/mylib"
]

but I couldn't notice any change and the auto import still does not work.


Solution

  • What finally worked for me is this setting:

        "python.analysis.extraPaths": [
            "~/Projects/mylib"
        ],
        "python.analysis.autoImportCompletions": false,
        "python.analysis.packageIndexDepths": [
            {
                "name": "mylib",
                "depth": 5,
                "includeAllSymbols": false
            }
        ],
        "python.autoComplete.extraPaths": [
            "~/Projects/mylib"
        ],
    

    With this, I can add missing imports simply with Cmd + . (on MacOS). If setting autoImportCompletions to true, it would even add the imports automatically.

    Thanks MingJie for the hint regarding the index depth. This was certainly a key issue. Not sure if the relative paths and the analysis.extraPaths was really needed, but now everything works.