58

It is a similar situation I'd encountered several months ago using pylint prior to pylance:

My python 3.9x - script (using VS Code on Ubuntu 20.04 LTS) starts with the following import of custom "tools":

import sys
sys.path.append(
    '/home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts/'
)

import General.Misc.general_tools as tools

Now, Pylance states:

Import "General.Misc.general_tools" could not be resolvedPylance (reportMissingImports)

This happens even though during the program execution the module is being imported perfectly fine.

Thus, to ensure making Pylance understand that this is an existing module-path, in addition to the sys.path.append(..) - approach, I added the following to the settings.json - file:

{
    ...
    // Possible values: "Jedi", "Pylance", "Microsoft", "None".
    "python.languageServer": "Pylance",
    // NOTE on changing from microsoft to pylance language server: python.autoComplete.extraPaths --> python.analysis.extraPaths
    // Docs: https://github.com/microsoft/pylance-release/blob/master/TROUBLESHOOTING.md#unresolved-import-warnings
    "python.analysis.extraPaths": [
        "/home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts"
    ],
    ...
}

Yet, I still get the reportMissingImports-message even though it's correctly being imported.

A workaround I found here works well (appending # type: ignore to the import-statement):

import General.Misc.general_tools as tools  # type: ignore

Nevertheless, it's just a workaround which is why I'm looking to solve the root of this issue. Technically, it is the same workaround I employed earlier to get rid of similar warning messages from pylint. Probably it's something inherent to the VS-Code settings.json - configuration, since using VS-Code is the constant factor here.


EDIT on additional measures which didn't resolve the problem:

I added

export PYTHONPATH="$PYTHONPATH:/home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts"

to my ~/.bashrc - file, which enables me now to import the module directly in a python-shell from terminal without the previous sys-path manipulation. This however applies only to the global system python environment, but not to any virtual environment. In order to change the sys-path there, I followed these instructions, while my particular virtual environment "scrapy_course" is open, like so:

(scrapy_course) andylu@andylu-Lubuntu-PC:~/$ add2virtualenv /home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts

This command applies for virtualenvwrapper, which mananges virtual environments in conjunction with pyenv neatly. Now, I can run my aforementioned script within the current environment even without the sys.path.append(...) prior to import the module, YET pylance still doesn't recognize the paths correctly and shows me the same warning as before.


EDIT on "python.analysis.useImportHeuristic": true:

I've had this option constantly activated in my global settings.json - file and still I didn't notice any effect. I will keep you updated once this should change, or finally a (different) solution crosses my way.


EDIT on suppressing/disabling the Pylance 'reportMissingImports' linting-message:

I've found out how to suppress a specific Pylance-linting-message altogether, if that is of your interest as a workaround. Especially in my current situation, I need to utilize pylint in parallel anyway, so I don't depend on Pylance's linter at all.

Andreas L.
  • 3,239
  • 5
  • 26
  • 65
  • 1
    will it resolve if you do `import General`, what if you add the path to `PYTHONPATH` before starting VSC. Maybe PyLance only wants relative paths in `"python.analysis.extraPaths"` – rioV8 Dec 11 '20 at 15:06
  • Thanks for your hint. It made me try out additional measures (see EDIT of my initial post above). I still get the same warning message from pylance. Apart from that, an absolute path should always work as far as I'm concerned, but even if this was the issue, now there are all `python`- and `sys`-paths set within my project-`venv`, and still `pylance` doesn't recognize it. – Andreas L. Dec 11 '20 at 22:00
  • then consider filing an issue with PyLance not adhering to `PYTONPATH`, but how do the virtual environments merge the local and system installed modules, PyLance can handle these – rioV8 Dec 11 '20 at 22:25
  • Now, for some reason, it stopped throwing the warnings. I don't know how it got resolved, but for now I closed the issue posted on the `pylance` GitHub website: https://github.com/microsoft/pylance-release/issues/724 – Andreas L. Jan 04 '21 at 18:09
  • i get the same linting issue. It appears as though there is still no solution other than to add `# type: ignore` at the end of the import statement. – D.L Apr 14 '21 at 22:01
  • I tried to recreate the issue (on Windows) but it works for me by adding the full path to `python.analysis.extraPaths`, the only case I get the error is when I change something in `General` (add a `.py` file). I need to restart VSC, PyLance probably assumes the files in the `extraPaths` are static – rioV8 Oct 21 '22 at 09:51

9 Answers9

58

Pylance, by default, includes the root path of your workspace. If you want to include other subdirectories as import resolution paths, you can add them using the python.analysis.extraPaths setting for the workspace.

  • In VS Code press <ctrl> + <,> to open Settings.
  • Type in python.analysis.extraPaths
  • Select "Add Item"
  • Type in the path to your library /home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts/
Ryan
  • 1,247
  • 1
  • 10
  • 12
  • 1
    Thanks for your reply. Yet, as you can see in my post, I've already tried that with no avail. Maybe it has an effect now. As soon as I get to try it out, I'll let you know. – Andreas L. Apr 13 '21 at 09:11
  • 2
    Is there a less specific solution? I mean, if I use this solution, I have to add all the paths to all the folders where any test scripts are located. – carloswm85 May 17 '21 at 17:25
  • 2
    I use virtualenv for my (Django) project and I had to reference the path for this to work: ~/.virtualenvs//Lib/site-packages/ – Paul Maurer May 19 '21 at 16:02
  • 2
    In addition to this, make sure to [select and activate the correct Python environment](https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment). – Gino Mempin May 30 '21 at 23:33
  • This works perfectly when the "source" folder is named something else than "src". – danielcaballero88 Jul 12 '21 at 11:57
  • Doesn't work for me on macOS and latest version of vscode using Pylance. My conda envs work fine though. – liquidRock Dec 13 '21 at 03:34
  • This solution worked for me where I have installed pylucene to be running via jcc. Earlier, the auto completion for package, e.g. `from org.apache.lucene.analysis.standard import StandardAnalyzer` was not working. This solution worked for me after a restart of the vscode. – Doi Jun 17 '22 at 21:10
29

Two methods below:

  1. In VS code you can edit the setting.json file. If you add "python.analysis.useImportHeuristic": true the linting error will be removed.

  2. The alternative is to add # type: ignore at the end of the import code.

Here is the github link that i got the above resolution from: https://github.com/microsoft/pylance-release/issues/68

It worked for me: python 3.9, VScode, windows10

D.L
  • 4,339
  • 5
  • 22
  • 45
  • Thanks for your contribution. I've also followed the git-discussion and saw the `"python.analysis.useImportHeuristic": true`, I'll try it out once I get to it. As for the 2nd alternative, this workaround was already mentioned in my initial post and seems to be the last resort, if nothing else works. – Andreas L. Apr 15 '21 at 07:54
  • comment noted. I confirm that both methods work on the setup that i have, although it seems that you are using `Lubuntu 20.04` whereas i tested on `windows10`. so would be useful to know that it is platform agnostic or otherwise. – D.L Apr 16 '21 at 10:06
  • 12
    Just checked it on Windows 10, in my `settings.json` the line `"python.analysis.useImportHeuristic": true` is greyed out. When I hover over it, it states "Unknown Configuration Setting". – Andreas L. Apr 19 '21 at 08:20
  • @AndreasL. Same happened to me when I got the `"Unknown Configuration Setting"`. Did you find a workaround for this? – Prakhar Rathi May 14 '21 at 19:07
  • @PrakharRathi not yet, I'll let you know here if there are any updates – Andreas L. May 15 '21 at 13:34
  • 5
    This is expected as it is a hidden option. https://github.com/microsoft/pylance-release/issues/1167#issuecomment-822647493 –  May 22 '21 at 12:54
  • 1
    I've revisited the issue today, and still there are import errors despite using `"python.analysis.useImportHeuristic": true` (see latest edit of my OP). I'll keep you guys updated. – Andreas L. Jun 24 '21 at 12:44
6

By default python selects the global interpreter as the interpreter for any python project you have. So the module/package resolution is in the global context. For any linter you are using to pick up your installed modules you have to ensure you select the correct interpreter

For instance, if you have ever worked with pycharm it does ask you to select the interpreter and create virtual environment with the selected interpreter. For the same, if you start a project in visual studio code It takes the global interpreter as the default interpreter even if you create a virtual environment See this on the bottom left section for the selected interpreter

enter image description here

So how do you ensure Pylance/Pylint/ reads modules installed in the virtual environment created? You need to check for the selected interpreter at the bottom left and if not activated on the virtual environment click on the selected interpreter and vs-code will prompt you to select a default interpreter for the project. Select your current virtual environment and visual studio pylance will read the modules in the current environment. Hope this works for anyone who's struggling with the same

enter image description here

enter image description here

Felix Orinda
  • 593
  • 4
  • 20
  • 1
    This works, but some of us are also trying to add other sys.paths outside of the current env, and Pylance will not recognize them, even if they are setup correctly and work when we run the py files. [This Example](https://stackoverflow.com/a/10739838/3927293) was the only thing that worked for me. – liquidRock Dec 13 '21 at 05:05
  • You can add those paths in the `./vscode/settings.json` from where vscode reads all configurations from if the `settings.json` is set – Felix Orinda Dec 30 '21 at 15:21
2

I was facing similar issue, even after having packages on my system, VS Code Pylance was not able to resolve imports.

In my case I had 2 different versions of python installed (one using anaconda distribution and other directly from python.org)

Fix: Select right python interpreter in VS code. Pylance will stop complaining :)

enter image description here

Tarun Kumar
  • 729
  • 1
  • 8
  • 16
1

Another option is to add an .env file at the root of the vscode project. For example:

.env

PYTHONPATH=src/mydir

You either use a relative path like above, or the full path. The benefit of .env is that it will fix both pylance and pylint in vscode. And it's easier to commit and share on git than .vscode/settings.json.

wisbucky
  • 33,218
  • 10
  • 150
  • 101
1

Pylance is the default the language server used for python project unless you specify it otherwise. If you get (reportMissingImports) and you are sure the dependency has been successfully installed, it means it's installed somewhere else than Pylance expected. This usually happens if you are working with virtual environements.

Pylance by default selects the system python interpreter for any python project, in this case you need to tell Pylance where to find the virtualenv python interpreter by defining this your vscode settings. Under .vscode/settings.json add the following:

{
    "python.defaultInterpreterPath": "~/.pyenv/versions/3.10.2/envs/<my-virtual-env-name>/bin/python",
    "python.linting.ignorePatterns": [
        "**/site-packages/**/*.py"
    ],
}

Now Pylance will know exactly where to look for the installed dependency. In my case I'm using pyenv but it may be any other path depending on what virtualenv tool you use. If you have other dependencies in other custom location, you can add them by specifying "python.analysis.extraPaths":

{
    "python.defaultInterpreterPath": "~/.pyenv/versions/3.10.2/envs/<my-virtual-env-name>/bin/python",
    "python.linting.ignorePatterns": [
        "**/site-packages/**/*.py"
    ],
    "python.analysis.extraPaths": [
        "my-custom-path-1/python/scripts", 
        "my-custom-path-2/something-else"
    ],
}
Dhia
  • 10,119
  • 11
  • 58
  • 69
0

If you are using Anaconda environment, a workaround is to add your personal library path to 'python library path' via the command conda develop path/to/your/module.

LinFelix
  • 1,026
  • 1
  • 13
  • 23
-1

Add this to your settings.json in vscode:

   "python.analysis.extraPaths": ["ml/py"],

it can be a relative path based on the root of your project or an absolute path. You can also have several of them.

David Dehghan
  • 22,159
  • 10
  • 107
  • 95
-1

In VS studio code

  1. Open your folder
  2. Right Click on the workspace where all the files or folders are
  3. Add folder to workspace
  4. Select the directory on what you inputted in sys.path.insert("DIRECTORY")
rioV8
  • 24,506
  • 3
  • 32
  • 49
  • why would a Multi Root Workspace solve the PyLance `reportMissingImports` problem, where in Explorer do you `right click`? **Add Folder to Workspace** is part of the **File** menu – rioV8 Oct 20 '22 at 07:24