Although you have done everything correctly, whenever you try to import a library or a class defined in that library, PyCharm fails to import it and fails to adding it to the code-sense, which is annoying because of the red line under the imported name, and because of the loss of the code-sense functionality which represents a major added value of using an IDE.
When you run the code, everything runs correctly despite the import errors which indicates that the interpreter is setup correctly but something is wrong with the editor.
There are several reasons why this could be happening. Below are several steps that fixes the majority of those cases:
.idea caching issue
PyCharm stores project details and definitions in a hidden folder: “
.idea” . issue causing the IDE to show error while the code still runs correctly. The solution here is to:
- Close the project and quick PyCharm;
- Delete the
.ideafolder 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 re-create the project.
Imports relative not to project folder
You might be attempting to import names using a “relative import” notation, however the “code root folder” in pycharm is not the same as the “project folder”. The solution here is to:
- Find the folder that relative imports require in the “project explorer”;
- Right click on it and mark it as “Source Root”
Editor not marking __init__.py as Python
This is the most illusive of all the cases. For some reason, the PyCharm editor considers
__init__.py files not to be python files, and thus ignores them during code analysis. To fix this you have to:
- Open PyCharm settings;
- Navigate to Editor -> File Types;
- Find “Python” and add
__init__.pyto the list of python files or find “Text” and delete
__init__.pyfrom the list of text files
That should fix the issue