Pylint "unresolved import" error in Visual Studio Code - python

I am using the following setup
macOS v10.14 (Mojave)
Python 3.7.1
Visual Studio Code 1.30
Pylint 2.2.2
Django 2.1.4
I want to use linting to make my life a bit easier in Visual Studio Code. However, for every import I have states "unresolved import". Even on default Django imports (i.e. from django.db import models).
I presume it is because it is not seeing the virtual environment Python files.
Everything works just fine, but it's starting to get annoying.
The interpreter choices I have are all system versions of Python. It does not seem to see my virtual environment Python at all (it is not in the same directory as my workspace, so that part makes sense).
If I set up the python.PythonPath in the settings.json file, it just ignores it and does not list my virtual environment path as an option. I also tried setting it up in my global Python settings, but it also does not show up.
Is there a quick fix to get it working?

The accepted answer won't fix the error when importing own modules.
Use the following setting in your workspace settings .vscode/settings.json:
"python.autoComplete.extraPaths": ["./path-to-your-code"],
Reference: Troubleshooting, Unresolved import warnings

In your workspace settings, you can set your Python path like this:
{
"python.defaultInterpreterPath": "/path/to/your/venv/bin/python",
}

Alternative way: use the command interface!
Cmd/Ctrl + Shift + P → Python: Select Interpreter → choose the one with the packages you look for:

This issue has already been opened on GitHub:
Python unresolved import issue #3840
There are two very useful answers, by MagnuesBrzenk and SpenHouet.
The best solution for now is to create a .env file in your project root folder. Then add a PYTHONPATH to it like this:
PYTHONPATH=YOUR/MODULES/PATH
And in your settings.json add:
"python.envFile": ".env"

When I do > reload window that fixes it.
Reference: Python unresolved import issue #3840, dkavraal's comment

None of the solutions worked except this one. Replacing "Pylance" or "Microsoft" in the settings.json solved mine.
"python.languageServer": "Jedi"

You need to select the interpreter associated with the virtual environment.
Click here (at the bottom status bar):
And just select the virtual environment you are working with. Done.
Sometimes, even with the interpreter selected, it won't work. Just repeat the process again and it should solve it.

If you have this code in your settings.json file, delete it:
{
"python.jediEnabled": false
}

If you are more visual like myself, you can use the Visual Studio Code configurations in menu File → Preferences → Settings (Ctrl + ,). Go to Extensions → Python.
In the section Analysis: Disabled, add the suppression of the following message: unresolved-import:

I was able to resolved this by enabling jedi in .vscode\settings.json
"python.jediEnabled": true
Reference from https://github.com/Microsoft/vscode-python/issues/3840#issuecomment-456017675

I wonder how many solutions this problem have (or have not), I tried most of the above, nothing worked, the only solution that worked is to set the python language server to Jedi, instead of Microsoft in the settings.json file:
"python.languageServer": "Jedi"

None of the previous answers worked for me. Adding both of the lines below to my settings.json file did, however.
"python.analysis.disabled": [
"unresolved-import"
],
"python.linting.pylintArgs": ["--load-plugin","pylint_protobuf"]
The first line really just hides the linting error. Certainly not a permanent solution, but de-clutters the screen.
This answer gave me the second line: VS Code PyLint Error E0602 (undefined variable) with ProtoBuf compiled Python Structure
Maybe someone who understands Python more than me can explain that one more.

Okay, so 2 years down the line, I have ran into this annoying problem. All I can seen here are some really complicated workarounds. Here are easy to follow steps for anyone else who might just run into this later on:
at the bottom of VS Code where you see the Python version listed, just click there
Select Interpreter windows is going to appear
click on the first option that says "Select Interpreter Path" and navigate to the folder path which has your Virtual Environment
That's all you need to do and avoid tampering with those settings in VS Code which might get very complicated if not handled with caution.

My solution
This solution is only for the current project.
In the project root, create folder .vscode
Then create the file .vscode/settings.json
In the file setting.json, add the line (this is for Python 3)
{
"python.pythonPath": "/usr/local/bin/python3",
}
This is the example for Python 2
{
"python.pythonPath": "/usr/local/bin/python",
}
If you don't know where your Python installation is located, just run the command which python or which python3 on the terminal. It will print the Python location.
This example works for dockerized Python - Django.

I was facing the same problem while importing the project-related(non standard) modules.
Detailed explanation of the problem
Directory structure:
Project_dir:
.vscode/settings.json
dir_1
> a
> b
> c
dir_2
> x
> y
> z
What we want:
Project_dir
dir_3
import a
import y
Here "import a" and "import y" fails with following error:
Import "dir_1.a" could not be resolvedPylancereportMissingImports
Import "dir_2.y" could not be resolvedPylancereportMissingImports
What worked for me:
Appending the top directory which contains the modules to be imported.
In above example add the follwoing "Code to append" in ".vscode/settings.json"
Filename:
.vscode/settings.json
Code to append:
"python.analysis.extraPaths": [dir_1, dir_2]

The solution from Shinebayar G worked, but this other one is a little bit more elegant:
Copied from Python unresolved import issue #3840:
Given the following example project structure:
workspaceRootFolder
.vscode
... other folders
codeFolder
What I did to resolve this issue:
Go into the workspace folder (here workspaceRootFolder) and create a .env file
In this empty .env file, add the line PYTHONPATH=codeFolder (replace codeFolder with your folder name)
Add "python.envFile": "${workspaceFolder}/.env" to the settings.json
Restart Visual Studio Code

To me the problem was related with the project that I was working on. It took me a while to figure it out, so I hope this helps:
Original folder structure:
root/
__init__.py # Empty
folder/
__init__.py # Empty
sub_folder_b/
my_code.py
sub_folder_c/
another_code.py
In another_code.py:
from folder.sub_folder_b import my_code.py
This didn't trigger the intellisense in Visual Studio Code, but it did execute OK.
On the other hand, adding "root" on the import path, did make the intellisense work, but raised ModuleNotFoundError when executing:
from root.folder.sub_folder_b import my_code.py
The solution was to remove the _init_.py file inside the "folder" directory, leaving only the _init_.py located at /root.

This works for me:
Open the command palette (Ctrl + Shift + P) and choose "Python: Select Interpreter".
Doing this, you set the Python interpreter in Visual Studio Code.

None of the answers here solved this error for me. Code would run, but I could not jump directly to function definitions. It was only for certain local packages. For one thing, python.jediEnabled is no longer a valid option. I did two things, but I am not sure the first was necessary:
Download Pylance extension, change python.languageServer to "Pylance"
Add "python.analysis.extraPaths": [ "path_to/src_file" ]
Apparently the root and src will be checked for local packages, but others must be added here.

I am using the following setup: (in Apr 2021)
macos big sur
vscode
Anaconda 3 (for environment)
And I faced this error during starting of the Django.
So, I follow these steps and this error is resolved.
Steps are given in these screenshots:
Open settings (workspace)
Follow this screenshot to open Python Path
Now, click Edit in settings.json
Make path like given in this screenshot /opt/anaconda3/bin/python
5. Now, save this settings.json file.
6. Restart the vscode
Also, intellisense might not work for some time hold on wait for some time and then restart again then vscode reads file for new path.

That happens because Visual Studio Code considers your current folder as the main folder, instead of considering the actual main folder.
The quick way to fix is it provide the interpreter path to the main folder.
Press Command + Shift + P (or Ctrl + Shift + P on most other systems).
Type Python interpreter
Select the path where you installed Python in from the options available.

Changing
Python:Language Server
to 'Jedi' worked for me.
It was 'Windows' initially.

For me, it worked, if I setup the paths for python, pylint and autopep8 to the local environment paths.
For your workspace add/change this:
"python.pythonPath": "...\\your_path\\.venv\\Scripts\\python.exe",
"python.linting.pylintPath": "...\\your_path\\.venv\\Scripts\\pylint.exe",
"python.formatting.autopep8Path": "...\\your_path\\.venv\\Scripts\\autopep8.exe",
Save and restart VS Code with workspace.
Done!

I have a different solution: my Visual Studio Code instance had picked up the virtualenv stored in .venv, but it was using the wrong Python binary. It was using .venv/bin/python3.7; using the switcher in the blue status bar.
I changed it to use .venv/bin/python and all of my imports were resolved correctly.
I don't know what Visual Studio Code is doing behind the scenes when I do this, nor do I understand why this was causing my problem, but for me this was a slightly simpler solution than editing my workspace settings.

In case of a Pylint error, install the following
pipenv install pylint-django
Then create a file, .pylintrc, in the root folder and write the following
load-plugins=pylint-django

I have faced this problem in three ways. Although for each of them a solution is available in the answers to this question, I just thought to put it all together.
First I got an "Unresolved Import" while importing some modules and I noticed that my installations were happening in global pip instead of the virtual environment.
This issue was because of the Python interpreter. You need to select the interpreter in Visual Studio Code using Shift + Ctrl + P and then type Select Python Interpreter. Select your venv interpreter here.
The second issue was: The above change did not resolve my issue completely. This time it was because of file settings.json. If you don't have the settings.json file in your project directory, create one and add the following line in that:
{
"python.pythonPath": "apis/bin/python"
}
This will basically tell Visual Studio Code to use the Python interpreter that is in your venv.
The third issue was while importing a custom Python module or file in another program. For this you need to understand the folder structure. As Python in venv is inside bin, you'll need to specify the folder of your module (most of the time the application folder). In my case it was app,
from app.models import setup_db
Verbally, import setup_db from models.py resides in the app folder.

If you are using pipenv then you need to specify the path to your virtual environment.in settings.json file.
For example :
{
"python.pythonPath":
"/Users/username/.local/share/virtualenvs/Your-Virual-Env/bin/python"
}
This can help.

If someone happens to be as moronic as me, the following worked.
Old folder structure:
awesome_code.py
__init__.py
src/
__init__.py
stuff1.py
stuff2.py
New structure:
awesome_code.py
src/
__init__.py
stuff1.py
stuff2.py

How to avoid warning
Please note that this is just skipping the warning not resolving it.
First of all open visual studio code settings in json and add following arguments after "[python]":{}
"python.linting.pylintArgs": ["--rep[![enter image description here][1]][1]orts", "12", "--disable", "I0011"],
"python.linting.flake8Args": ["--ignore=E24,W504", "--verbose"]
"python.linting.pydocstyleArgs": ["--ignore=D400", "--ignore=D4"]
This has helped me to avoid pylint warnings in VSCode.

I have resolved import error by Ctrl + Shift + P.
Type "Preferences settings" and select the option Preferences Open Settings (JSON)
And add the line "python.pythonPath": "/usr/bin/"
So the JSON content should look like:
{
"python.pythonPath": "/usr/bin/"
}
Keep other configuration lines if they are present.
This should import all modules that you have installed using PIP for autocomplete.

Related

Set PYTHONPATH with PyCharm using remote interpreter [duplicate]

I have a directory structure
├── simulate.py
├── src
│   ├── networkAlgorithm.py
│   ├── ...
And I can access the network module with sys.path.insert().
import sys
import os.path
sys.path.insert(0, "./src")
from networkAlgorithm import *
However, pycharm complains that it cannot access the module. How can I teach pycham to resolve the reference?
Manually adding it as you have done is indeed one way of doing this, but there is a simpler method, and that is by simply telling pycharm that you want to add the src folder as a source root, and then adding the sources root to your python path.
This way, you don't have to hard code things into your interpreter's settings:
Add src as a source content root:
                           
Then make sure to add add sources to your PYTHONPATH under:
Preferences ~ Build, Execution, Deployment ~ Console ~ Python Console
Now imports will be resolved:
                     
This way, you can add whatever you want as a source root, and things will simply work. If you unmarked it as a source root however, you will get an error:
                                 
After all this don't forget to restart. In PyCharm menu select: File --> Invalidate Caches / Restart
check for __init__.py file in src folder
add the src folder as a source root
Then make sure to add sources to your PYTHONPATH (see above)
in PyCharm menu select: File --> Invalidate Caches --> Restart
If anyone is still looking at this, the accepted answer still works for PyCharm 2016.3 when I tried it. The UI might have changed, but the options are still the same.
ie. Right click on your root folder --> 'Mark Directory As' --> Source Root
After testing all workarounds, i suggest you to take a look at Settings -> Project -> project dependencies and re-arrange them.
Normally, $PYTHONPATH is used to teach python interpreter to find necessary modules. PyCharm needs to add the path in Preference.
There are several reasons why this could be happening. Below are several steps that fixes the majority of those cases:
.idea caching issue
Some .idea issue causing the IDE to show error while the code still runs correctly. Solution:
close the project and quick PyCharm
delete the .idea folder where the project is. note that it is a hidden folder and you might not be aware of its existence in your project directory.
start PyCharm and recreate the project
imports relative not to project folder
Relative imports while code root folder is not the same as the project folder. Solution:
Find the folder that relative imports require in the project explorer
right click and mark it as "Source Root"
Editor not marking init.py as Python but as Text
Which is the most illusive of all the cases. Here, for some reason, PyCharm considers all __init__.py files not to be python files, and thus ignores them during code analysis. To fix this:
Open PyCharm settings
Navigate to Editor -> File Types
Find Python and add __init__.py to the list of python files
or
Find Text and delete __init__.py from the list of text files
The project I cloned had a directory called modules and was successfully using files from there in the code with import this as that, but Pycharm was unable to jump to those code fragments because it did not recognise the imports.
Marking the module folder in the following settings section as source solved the issue.
Generally, this is a missing package problem, just place the caret at the unresolved reference and press Alt+Enter to reveal the options, then you should know how to solve it.
Although all the answers are really helpful, there's one tiny piece of information that should be explained explicitly:
Essentially, a project with multiple hierarchical directories work as a package with some attributes.
To import custom local created Classes, we need to navigate to the directory containing .py file and create an __init__.py (empty) file there.
Why this helps is because this file is required to make Python treat the directory as containing packages. Cheers!
Install via PyCharm (works with Community Edition). Open up Settings > Project > Project Interpreter then click the green + icon in the screenshot below. In the 2nd dialogue that opens, enter the package name and click the 'Install Package' button.
After following the accepted answer, doing the following solved it for me:
File → Settings → Project <your directory/project> → Project Dependencies
Chose the directory/project where your file that has unresolved imports resides and check the box to tell Pycharm that that project depends on your other project.
My folder hierarcy is slightly different from the one in the question. Mine is like this
├── MyDirectory
│     └── simulate.py
├── src
│     ├── networkAlgorithm.py
│     ├── ...
Telling Pycharm that src depends on MyDirectory solved the issue for me!
This worked for me: Top Menu -> File -> Invalidate Caches/Restart
--> Right-click on the directory where your files are located in PyCharm
Go to the --> Mark Directory as
Select the --> Source Root
your problem will be solved
Many a times what happens is that the plugin is not installed. e.g.
If you are developing a django project and you do not have django plugin installed in pyCharm, it says error 'unresolved reference'.
Refer:
https://www.jetbrains.com/pycharm/help/resolving-references.html
I was also using a virtual environment like Dan above, however I was able to add an interpreter in the existing environment, therefore not needing to inherit global site packages and therefore undo what a virtual environment is trying to achieve.
Please check if you are using the right interpreter that you are supposed to. I was getting error "unresolved reference 'django' " to solve this I changed Project Interpreter (Changed Python 3 to Python 2.7) from project settings:
Select Project, go to File -> Settings -> Project: -> Project Interpreter -> Brows and Select correct version or Interpreter (e.g /usr/bin/python2.7).
In my case the problem was I was using Virtual environment which didn't have access to global site-packages. Thus, the interpreter was not aware of the newly installed packages.
To resolve the issue, just edit or recreate your virtual interpreter and tick the Inherit global site-packages option.
Done in PyCharm 2019.3.1
Right-click on your src folder -> "Mark Directory as" -> Click-on "Excluded" and your src folder should be blue.
I tried everything here twice and even more. I finally solved it doing something I hadn't seen anywhere online. If you go to Settings>Editor>File Types there is an 'Ignore Files and folders' line at the bottom. In my case, I was ignoring 'venv', which is what I always name my virtual environments. So I removed venv; from the list of directories to ignore and VOILA!! I was FINALLY able to fix this problem. Literally all of my import problems were fixed for the project.
BTW, I had installed each and every package using PyCharm, and not through a terminal. (Meaning, by going to Settings>Interpreter...). I had invalidated cache, changed 'Source Root', restarted PyCharm, refreshed my interpreters paths, changed interpreters, deleted my venv... I tried everything. This finally worked. Obviously there are multiple problems going on here with different people, so this may not work for you, but it's definitely worth a shot if nothing else has worked, and easy to reverse if it doesn't.
For my case :
Directory0
├── Directory1
│ └── file1.py
├── Directory2
│ ├── file2.py
Into file1, I have :
from Directory2 import file2
which trows an "unresolved reference Directory2".
I resolved it by:
marking the parent directory Directory0 as "Source Root" like said above
AND
putting my cursor on another line on the file where I had the error so that it takes my modification into account
It is silly but if I don't do the second action, the error still appears and can make you think that you didn't resolve the issue by marking the parent directory as Source Root.
For me, adding virtualenv (venv)'s site-packages path to the paths of the interpreter works.
Finally!
I had the same problem and also try so many suggestions but none of them worked, until I find this post (https://stackoverflow.com/a/62632870/16863617). Regardless his solution didn't work for me, it helped me to came up with the idea to add _init.py_ into the --> Settings | Editor | File Types | Python | Registered patterns
ScreenShot
And the unresolved reference error is now solved.
just note if u have a problem with python interpreter not installing
packages, just change the permission for folder PycharmProjects
C:\Users'username'\PycharmProjects
to every one
This problem also appears if you use a dash within the Python filename, which therefore is strongly discouraged.
I encountered an import problem when installing aiogram. At the same time, the bot worked, but pyCharm highlighted the import in red and did not give hints. I've tried all of the above many times.As a result, the following helped me: I found the aiogram folder at the following path
c\Users...\AppData\Roaming\Python\Python310\site-packages
and copied it to the folder
C:\Program Files\Python310\Lib\site-packages
After that, I reset pyCharm and that's it!
In my case, with Pycharm 2019.3, the problem was that I forgot to add the extension '.py' to the file I wanted to import. Once added, the error went away without needing to invalides caches or any other step.
Pycharm uses venv. In the venv's console you should install the packages explicitly or go in settings -> project interpreter -> add interpreter -> inherit global site-packages.
The easiest way to fix it is by doing the following in your pyCharm software:
Click on: File > Settings > (Project: your project name) > Project Interpreter >
then click on the "+" icon on the right side to search for the package you want and install it.
Enjoy coding !!!
In newer versions of pycharm u can do simply by right clicking on the directory or python package from which you want to import a file, then click on 'Mark Directory As' -> 'Sources Root'

How do I get into the environment VS Code is using for pylance?

I'm using pylance to check my Python code. It tells me
Import "astor" could not be resolved
When I switch to the terminal within VS Code:
I'm pretty certain that the issue is that it uses another environment. I'm using pyenv by default and I would like if vscode would use the same environment. But at the very least I need to be able to access the environment it is using to install packages.
Interestingly, the status bar seems to show something else, because in that environment I have astor installed:
I found this link that informs us that we should add an extra path.
These extra roots must be specified to the language server. The
easiest way to do this (with the VS Code Python extension) is to
create a workspace configuration which sets
python.analysis.extraPaths. For example, if a project uses a sources
directory, then create a file .vscode / settings.json in the workspace
with the contents:
{
"python.analysis.extraPaths": ["./sources"]
}
https://github.com/microsoft/pylance-release/blob/master/TROUBLESHOOTING.md#unresolved-import-warnings
Another easy way to solve this on VSCODE:
ctrl + ','
type "extrapaths"
Down you should have something like "add element" (I have VSCode on Spanish so in my case I have "Agregar elemento")
type './sources/'
Also if you have problems importing local files, you can do the same thing and add your working directory path to solve the problem :) just add 'C: your working directory goes here' in addition to './sources' in the same way ;)
I found one thing resolved my issue same as yours
Go to your working env(mine is pipenv shell), then pip show 'yourmodule' to check your module is installed or not
If its installed copy Location: path
Go to settings ctrl +','
Type extrapaths
Add Item paste the path string you copied and ok.
We have added actual installed path as additional import search resolution path, so this path will be scanned for imports
Now your module should be resolved. This worked for me.

Adding to PYTHONPATH in VS Code

I'm trying to add the src folder to my PYTHONPATH i.E. do the same thing as Mark directory as sources root in PyCharm.
I've looked at the solutions to Visual Studio Code - How to add multiple paths to python path? but the solutions shown there do not work for me.
I've set up my minimal example as follows shown in the screenshot below:
My understanding would be that having a .env file with PYTHONPATH="./src;${PYTHONPATH}" would add the src file to the path.
Nevertheless, when running the code runner or when running python change_pyhton_path.py src is not part of the PYTHONPATH and the direct import from src fails.
I do have setting "python.envFile": "${workspaceFolder}/.env".
In pyCharm on the other hand everything works as it should after hitting Mark directory as source on src.
Thanks for helping out!
in your settings.json add:
"terminal.integrated.env.windows": {
"PYTHONPATH": "full python path here"
}
if you have problems with importing modules and you are using code-runner, try to add
"code-runner.fileDirectoryAsCwd": true
to your settings.json file
If you are trying to get auto complete working from your source directory, you could add to the PYTHONPATH environment variable as you are doing. You can also go the "vscode native" route, as there is a configuration. Open your workspace settings and add the following line:
"python.autoComplete.extraPaths": ["./src"]
NOTE: Avoid setting this at the user level as each project differs in where the source code lives
I dont know much but the json PYTHONPATH setting above looks like it would work as the json.settings file is definatly going to nead to know about your interpreter. Once you have a Python terminal prompt you have to run pythons pip file to integrate all the neccesary libraries . VS Code itself tells you to go to the command pallete and install either a venv virtual environment or create a conda (from anaconda or miniconda) set up for it. I am trying to do it myself so once I crack it I'll have more info.

in IntelliJ, showing "No module named xxx", but "xxx" is actually installed in my system

My IntelliJ version is 15.0.3, and have python plugin installed.
And when I open a python file in IntelliJ it's like below
Situation here is like below:
when I import these flagged modules in terminal, everything works fine.
running this python file in IntelliJ, is also fine
It's only the red underlying warning annoying me.
I tried this one, this one and this one, but none works for me.
Could anyone please tell me how to get rid of it? Thanks a lot.
You have to add the site-packages path of your interpreter.
For that you have to:
go to Project Structure
choose Global Libraries
choose your Python interpreter
press + at the upper left corner
choose the site-package path of your interpreter
choose "Classes"
also add your python interpreter root directory in the same way.
I have similar problems: cannot import manually installed module. I try to add classpath in Mac environment parameters and intellij SDKs, but it doesn't work. My final solution is to add the classpath of the module to Run/Debug Configurations:
Open Run/Debug Configurations and select your unittest class:
Run --> Edit Configurations...
Add your module's classpath to Environment variables:

Pycharm unresolved reference in virtualenv

When I started a new project in Pycharm using virtual environment, I got an unresolved reference warning message.
But I have installed django to my virtual environment and this code is working correctly.
How can I fix this? I'm using PyCharm 4.5.2 Pro
Open your project in pycharm and follow the step:
click on file(on top) > settings > project interpreter > add local > select virtualenv
OR
Make sure your project is a root directory, make it is the root directory.
I eventually stumbled across a method that worked for me, but I don't know the underlying problem.
Initially I created a virtualenv with PyCharm in the interpreter options. Annoyed that I was having this problem, I deleted it and just created a virtualenv with the virtualenv command, but the problem remained.
Then I went back to the interpreter selector and picked "add local". I navigated to the python binary in the /bin folder of the virtualenv I created and selected it. After this, the unresolved references were fixed.
I think your problem is like mine. I tested import matplotlib in the python shell, and it works, but in Pycharm it shows an error. This is because Pycharm doesn't know the path of site-packages.
To fix this, you can do one of the following:
Add the path of site-packages (for me C:\Program Files\Python 3.5\lib\site-packages) to PATH.
Go to File -> Settings -> Project Interpreter, then choose Python real path instead of venu path.
In your code add the following:
.
import sys
sys.path.append(r"C:\Program Files\Python 3.5\lib\site-packages")
import matplotlib.pyplot as plt
I think it will help you :)
File > Settings > Project > Project Structure
Double Click on the folder link under Content Root, and do OK.
Check your project root directory. Maybe problem in it.
And did you create virtualenv manually or through PyCharm?

Categories

Resources