Search code examples
pythonvisual-studio-codepylance

VSCode "Import X could not be resolved" even though listed under `help('modules')`


I'm on day 1 of Python and trying to import SciPy into a project. I installed it via pip install on ElementaryOS (an Ubuntu derivative). I have verified it's existence via:

$ python
>>> help("modules")

The exact error I'm getting is:

Import "scipy" could not be resolved Pylance (reportMissingImports)

When searching for this error I found:

  1. Import could not be resolved/could not be resolved from source Pylance in VS Code using Python 3.9.2 on Windows 10 Powershell -- the accepted answers all pointed towards a project specific .env file. I have no such project structure, nor does it make sense to me that one would be needed.

  2. A github issue -- this issue ends with "it just fixed itself"

When I run my program, I get no errors in console. And looking up "Pylance" it appears to be a Microsoft product. I suspect that VSCode is failing to lint correctly. Potentially because pip installed something in a place it wasn't expecting. This is my guess, but any help would be very much appreciated.


Edit: Following through on the idea of missing paths, I found this post -- How do I get into the environment VS Code is using for pylance?

Having added the path to where my modules can be found has yielded no results, though I'm not sure if the formatting is correct. Perhaps it needs glob syntax (eg path/**/*)

enter image description here


Solution

  • The issue was indeed with Pylance. It was missing an "additional path" to where pip had installed the projects I wanted to import. To solve the issue:

    First make sure you know the location of your import; you can find it with:

    $ python
    >>> import modulename
    >>> print(modulename.__file__)
    

    Then, once you know the location:

    1. Open settings (ctrl + ,)
    2. Search "pylance" or find it under "Extensions > Pylance"
    3. Find the "Extra Paths" config item
    4. Use "add item" to a add a path to the parent folder of the module. It will not do any recursive tree searching

    And you should be good to go!

    For a further example, you can see the image above where I had added the path /home/seph/.local/lib/python2.7/ to no avail. Updating it to /home/seph/.local/lib/python2.7/site-packages/ did the trick.