Often times, when developing with Python, we encounter errors related to third party module not found in our development environment. These are generally known as “no module named errors”. In this tutorial we would like to answer several questions related to the topic, so you can easily tackle those issues when trying to import and use third party libraries in Python.
Why is Python displaying the modulenotfounderror?
The Python programming language capabilities are mainly delivered as part of the so called Python Standard Library. That said, much of the key capabilities that we use in the area of Data Analysis are not part of the core library and are delivered as part of a third party library. Examples of such libraries are Pandas, Numpy, Seaborn, BeautifulSoup, Django, Requests, tkinter, tensorflow and others.
Whenever our code tries to import such a library for using it in our Python program, and can’t find it in the file system, we get the no module found error.
Here’s an example of the error message when trying to import cv2 into our development environment, in this case Jupyter Notebooks. You’ll find similar errors when working with other Python IDEs such as VSCode, Spyder, IDLE, Google Colab, PyCharm and others.
How do i fix the no module named error in Python?
We typically fix the error by adding the third party library into our development environment using the Python package installer (PIP) utility.
Using PIP is relatively straightforward:
- Save your work and close your development environment.
- Open your Windows command prompt or Terminal in macOSc.
- (Windows only) – Navigate to the path to your Python.exe (this step is redundant if you have already added Python to your Windows Path.
- Run pip in the following way:
pip install <third_party_module_name>
For example, if we are missing the cv2 (computer vision) capabilities:
pip install cv2
- Open your IDE and import the third party module in your Python script.
How do i add a module to Python if i run Anaconda?
Many Data Analysis practitioners use the pre built Anaconda distribution or its minimalist version – MiniConda. If you are using any of the Conda based distribution – you can proceed as following:
- First go ahead and activate your Anaconda environment, by typing the following command in the Windows Anaconda Prompt or Terminal for Linux and macOS:
conda activate <your_environment_path>
- You can then go ahead and use conda to update your environment:
conda install <third_party_module_name>
- Last, reopen your Python editor and import your module.