How to fix Python ImportError in PyCharm
An annoying error and how to get rid of it
ImportErrors can be among the most annoying in python for beginners as they can be notoriously difficult to debug. This is in particular the case since many such errors are not a problem with your code, but with your IDE settings. In this article we look at some ImportError problems in Python and how to fix them. I am using PyCharm for this, but similar solution strategies should apply to other IDE (such as VS Code,…) as well.
If you have ever gotten this response from your code, you know how annoying it can be:
ImportError: No module named xyz found
This can happen both for python libaries that you want to use (like
local modules that you are trying to import. Moreover, the problem can either be in
your python code or in your IDE. Lets see both cases.
Python reasons for this problem
Libaries not working
First make sure that the python interpreter for the project is the one that you intended to use. In the lower right corner of your PyCharm it should list
the interpreter. You can also go
Project Interpreter. From there you can also use the GUI to install packages directly.
Local modules not found
It can also happen
IDE reasons for this problem
I had even stranger case where:
from folder1.folder2.folder3.my_python_file import this_function # worked
from folder1.folder2.folder3.my_python_file import that_function # didn't work
What helps in this case is to repair the IDE. In PyCharm click
Repair IDE and follow the steps there. This will lead to a rebuild of the python index
which should help PyCharm to see the respective files.