Tailored quoteLeave a short request: we reply the same day and send a written quote within 1 business daySame-day reply · quote in 1 business dayGet a quote
Software

ModuleNotFoundError: No module named in Python, How to Fix It

Talha Aslan 19 min read 4 views

What is ModuleNotFoundError and what should you do first?

ModuleNotFoundError is the error Python raises when an import line names a module that it cannot find in any folder it searches. Usually the package is missing, or the Python that runs your code is not the one you installed it into. Your first step is to confirm which interpreter runs and whether the package lives there.

This guide covers one problem only: the No module named message and where to start when you see it. We give the diagnostic order we use in the field, from the most common cause to the rarest. First check the interpreter, because in most cases the package itself is fine and the interpreter is wrong.

It also helps to know the shape of the error. ModuleNotFoundError is a subclass of ImportError. In other words, Python tells you specifically that the module was not found at all. For the official details, see the Python import system reference.

What is the quick fix for ModuleNotFoundError in the first five minutes?

The steps below run from the most likely cause to the least likely one. Rerun your code after each step and watch whether the message changes.

  1. Note the module name in the message and check its spelling.
  2. Run python -m pip --version and confirm the path belongs to the Python you expect.
  3. Install the package with python -m pip install package-name, using the same Python that runs your code.
  4. If you use a virtual environment, activate it first and try again.
  5. If you use an editor or Jupyter, check the selected interpreter and kernel.
  6. Make sure none of your own files has the same name as the module.
  7. For your own project modules, run the file from the project root, as a module.

The third step solves most cases. If it does not, the sections below take each cause one by one. We chose this order on purpose, because people who see ModuleNotFoundError usually reinstall the package first and never check which Python received it.

How do you read the error message correctly?

The message has two parts: the module name and, sometimes, an extra note. The most common form is the No module named line with the name in quotes. That name is exactly what Python looked for, so read it carefully before you change anything.

Watch for dotted names. For example, a message about a submodule can mean that the parent package exists but the submodule does not. Sometimes a ModuleNotFoundError message ends with a note that the parent is not a package. In that case, a file with the same name as the real package usually shadows it.

Also read the traceback lines above the last one. They show which file and line triggered the import. Also, that tells you whether the problem sits in your own code or inside a library you installed. For a general approach, see our debugging techniques guide.

Note: stay patient while you read. Trying random commands in a hurry can make the environment messier. Change one thing per step, then watch the result. That way you know exactly what worked.

Is the package really installed, and in which Python?

This is the cause we meet most often. A computer can hold several Pythons: the system one, one from a package manager, a separate install, and one virtual environment per project. So the pip install command targets one of them, while your code may run on another.

The fix is simple. Call pip through the interpreter that runs your code, instead of calling pip directly. Then install and run always use the same Python. So these three lines make the situation clear.

python -c "import sys; print(sys.executable)"
python -m pip --version
python -m pip show package-name

The first command prints the path of the running Python. The second shows which Python pip belongs to. The third tells you whether the package is installed and where. If the two paths differ, you have found the problem.

On some systems the command is named python3. In that case, type python3 in place of python above. Also, avoid adding packages with pip to the Python that your operating system manages, because some systems block this on purpose. Open a separate environment for every project instead. Then the pip user guide explains the installation methods.

What happens when your virtual environment is not active?

A virtual environment is a folder that keeps a project's packages apart from the system. If you run code without activating it, the terminal uses the system Python. The packages sit inside the environment, so your code cannot see them.

The easiest sign is the environment name at the start of the prompt. To be sure, run the sys.executable command above. In practice, if the path points into your project's environment, activation worked.

These steps create and use a new environment:

python -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt

On Windows the activation script sits in a different folder. Moreover, you can find the details in the venv documentation. Moreover, if you move an environment folder to another place, its scripts may still point to old paths. The cure is to recreate the environment, not to move it. For anyone who forgets to activate, the safest habit is to always type python -m pip.

Could your editor be using the wrong interpreter?

Yes, and it is very common. Code editors and IDEs use their own selected interpreter when you press the run button. You install the package in the terminal, but the editor runs another Python. The error then shows up in the editor only, while the terminal runs the code without trouble.

To tell the cases apart, run the same file in the terminal with the active environment. For example, if it works there, the problem sits in the editor setting. Then open the interpreter selection of your editor and pick your project's environment. Menu names change between tools, so we do not quote exact button text. Look for the interpreter section in your tool's own documentation.

Also separate the linter from the actual run. If the editor underlines an import in red but the program runs fine, the analysis engine is probably looking at the wrong environment. In that case the problem is only in the display.

Why does a Jupyter notebook use a different Python?

Notebooks run on a kernel, and each kernel is tied to one Python installation. Activating an environment and installing a package in the terminal does not change the notebook kernel. Then that is why an import can work in the terminal and fail in the notebook.

First, run this in a notebook cell and read the path:

import sys
print(sys.executable)

If the path does not point to the environment you expect, switch the kernel or register a new kernel for that environment. With the environment active, you can register one using python -m ipykernel install --user --name project-env. To install inside a notebook, start a line with the percent sign and write %pip install package-name. In practice, that command installs into the kernel's own Python.

After the install you may need to restart the kernel. Otherwise the old state stays in memory and the error continues. If you are just starting with AI work in Python, our Python AI roadmap also touches on this environment setup.

Why can the package name differ from the import name?

The install name and the import name are not always the same. The name you give to pip is the distribution name, while the one you write in code is the module name. A difference between the two is legal and quite common.

Name you install with pipName in the import line
PillowPIL
scikit-learnsklearn
PyYAMLyaml
beautifulsoup4bs4
python-dotenvdotenv
opencv-pythoncv2

This list is only an example, not a tool recommendation. Also, you will find the correct import name for your package in its official documentation. If you install under a wrong name, you either get an error or you install a different package with a similar name. So copy the install command from the package's own page.

If you want to know the popular libraries better, see our article on the most popular Python libraries.

What if your own file has the same name as the module?

This is called shadowing. When Python imports, it looks first in the folder of the script you run. Suppose that folder holds a file named random.py or requests.py. Python then loads your file instead of the real module. As a result, an attribute goes missing or a strange ModuleNotFoundError appears.

The symptom is this: the package looks installed and pip show is correct, yet the import still fails. For example, someone who creates requests.py by accident sees ModuleNotFoundError or AttributeError and cannot find the cause. So when an error looks strange, list your folder first. To diagnose it, print the file from which a module loaded:

python -c "import json; print(json.__file__)"

If the path points to your project folder instead of the standard library or the site-packages folder, shadowing is the cause. Rename your file and delete old cache folders. To avoid the problem, never give your files the names of standard library modules or popular packages. Avoid names like test.py or email.py even in quick prototypes.

Why do project layout and relative imports fail?

For your own modules, the problem is usually how you run the code. Python builds the import path from where you start the script. If you run a file directly from a subfolder, the project root does not enter the path. A module in a sibling folder is then not found.

Example scenario: the project root holds a package named app with a file service.py. So you run that file from inside the subfolder, and another module cannot be found. Also, if you run the same file as a module from the project root, the problem goes away.

python -m app.service

The -m flag tells Python to run the file as a module, not as a path. The command line documentation explains the flag.

Historically, an __init__.py file marks a folder as a package. Modern Python also treats folders without it as namespace packages. Still, adding an empty __init__.py is a safe and clear choice if you want an explicit package.

What is the difference between relative and absolute imports?

An absolute import writes the full path of the package. A relative import uses dots to give a path from the package you are in. Relative imports work only inside a package, in files that run as modules. Then if you run the file directly as a script, a relative import fails.

For that reason, absolute imports are safer in your application's entry file. Moreover, if you turn your project into an installable package, the import path stays the same in every environment. Installing the project in editable mode during development is the practical way to do that. For the steps, see the Python Packaging User Guide.

In short, you can follow this rule: run the entry point from the project root with -m, and prefer absolute imports inside the package.

What is PYTHONPATH and when do you need it?

PYTHONPATH is an environment variable that lists extra folders Python searches for modules. Python looks first in the folder of the running script, then in the folders from this variable, and last in the standard library and site-packages. A folder you add to it joins the import path.

Even so, we do not recommend PYTHONPATH as the first fix. This setting depends on the machine, so it goes missing on another computer or in CI. Then the code works for you and fails for your teammate. Fix the package layout first, then make the project installable.

For a quick experiment, you can set the variable for a single command only. That is less risky, since it does not become a permanent setting. To see whether the path was really added, run python -c "import sys; print(sys.path)" and read the list.

In short, treat PYTHONPATH like a patch. The real cure is a correct project layout that prevents ModuleNotFoundError at its source. Moreover, that way the code behaves the same in every environment.

Why does ModuleNotFoundError appear in Docker and CI?

A ModuleNotFoundError in a container has a simple cause. So these environments start from a blank page. Every package you installed by hand on your computer is missing from the image or the CI runner. So code that works locally can fail at runtime. Most often the requirements file is incomplete.

  • The requirements file is stale, and a newly added package never reached it.
  • Your install step runs in the wrong order relative to copying the code.
  • One image holds more than one Python, and the command calls another one.
  • A different working directory means project imports are not found.
  • Finally, the CI cache restores an old environment.

To fix it, write your requirements to a file with python -m pip freeze > requirements.txt. Then run python -m pip install -r requirements.txt in the image. If containers are new to you, our Docker guide explains the basics.

Note: for safety, review your requirements files and install packages only from sources you know.

How do you read the symptom, cause and fix table?

The table below links the symptom you see to a likely cause and a first fix. The most likely cause sits at the top.

SymptomLikely causeFirst fix
Package just installed but import failsInstall went to another PythonReinstall with python -m pip install
Works in terminal, fails in editorEditor uses another interpreterSelect the environment in the editor
Works in terminal, fails in notebookKernel bound to another PythonSwitch kernel or install inside the notebook
Error persists with environment openEnvironment inactive or brokenActivate it, or recreate it
pip show is right, import is wrongFile name shadows the moduleRename your own file
Your own module is not foundRun from the wrong directoryRun from the root with -m
Relative import errorFile runs as a scriptUse absolute imports
Fails only in Docker or CIRequirements file incompleteUpdate the file, rebuild the image

Why does the install look successful but the import still fails?

This case is confusing, yet it has few causes. For example, the install output shows success, pip show lists the package, and the import still fails. Rule out these three possibilities in order.

  • The environment you installed into differs from the one that runs the code.
  • The running session started before the install, so a notebook or interactive shell was not restarted.
  • A local file with the same name shadows the package.

Next, check whether the installed package even offers an importable module. Some distributions install only a command line tool. The package's official documentation states this clearly.

Finally, check caches and leftovers. A half-removed folder from an old install can shadow the new one. Recreating the environment cleanly removes this possibility for good.

Could the Python version or install method hide the package?

Sometimes a package installs but the active Python cannot load it. In practice, the Python version the package supports may not match yours. In that case pip usually warns you during install, but the warning is easy to miss in the terminal output.

Read the install output from top to bottom. A success message and a partial error can appear in the same output, so do not glance at the last line only. In practice, you find the official version support in each package's own page. We do not list version numbers here, since this information changes often.

Another possibility is a per-user install. When you have a permission problem, some systems install the package into a user-specific folder. A virtual environment removes this confusion, because it writes into its own folder.

What changes if you use Conda or another package manager?

Tools like Conda bring their own environments and their own Pythons. In such an environment, pip and conda can install the same package to different places. As a result, the package shows up twice, but the active environment uses only one of them.

The rule is simple: pick one main manager per environment. Try installing the package with that manager first. If it is not available, call pip inside the same environment, in the form python -m pip. That keeps the two systems from installing without knowing about each other.

If your environment is already tangled, the cleanest cure is to create a new one and reinstall from the requirements file. Also, that takes a few minutes, and it costs less than hours of guessing.

Why does ModuleNotFoundError show up only in tests?

A ModuleNotFoundError in tests has a simple cause. Test tools use their own working directory and import rules. Your code may run fine in the app, while your own module is not found in a test. Then the test file sits in another folder, and the project root never entered the import path.

Example scenario: a file in the tests folder imports the app package, but the project root is not on the path. Installing the project in development mode is the cleanest fix. Then the package is found everywhere under the same name, and no path tweak is needed.

The test tool's own config file can also add paths. Use that only if the project layout truly needs it. Otherwise, the problem is hidden and returns in another form in CI.

How do you tell this error apart from ImportError and similar ones?

The class name at the start of the message guides you. ModuleNotFoundError says the module was not found at all. ImportError says the module was found but the requested name could not be taken from it. So the fixes differ.

  • ModuleNotFoundError: the module is not on the path, so check install, environment or file layout.
  • ImportError (cannot import name): the module exists but the name does not, which suggests a version mismatch or a circular import.
  • AttributeError: the module loaded but lacks the attribute, which often signals shadowing.
  • pip dependency conflict: it happens at install time, not at import time.

So read the class name first, then go to the matching section. In circular imports the message can mislead. If two modules import each other, you see ImportError rather than ModuleNotFoundError. The root cause is still the layout, and you fix it by moving shared code into a third module.

What changes when you work on a server or a remote machine?

On a server, the Python version, the installed packages and the environment variables differ from your computer. When you copy code over and run it, an import that worked locally can fail. First verify which Python gets called on the server.

If you have login problems while connecting to a remote machine, see our separate article on the SSH publickey error. Scheduled jobs and services also run in a different environment. Services do not inherit your active environment automatically, so give the full path of the Python.

You see similar environment trouble on the Node.js side. Our npm ERESOLVE guide covers dependency conflicts, and the JavaScript heap guide covers memory limits.

Which habits prevent this error for good?

Fixing the ModuleNotFoundError once is not enough, because you want to stop it from coming back. Then the habits below are the ones our team recommends most often in the field.

  1. Create a separate virtual environment for every project, and never install into the system Python.
  2. Always install packages with python -m pip.
  3. Keep dependencies in a requirements file and update it after every new package.
  4. Never name your files after standard library modules.
  5. Run your project from the root with -m.
  6. Pin the editor and notebook settings to the project's environment.
  7. State the Python version explicitly in Docker and CI scripts.

These seven habits prevent most of the ModuleNotFoundError cases we see. That is an observation from experience, not a statistic. Also, if you use Git, keep the environment folder out of version control and commit only the requirements file. For the basic commands, see our Git and GitHub guide.

Which checklist should you use while diagnosing?

When ModuleNotFoundError blocks you, walk through the list below from top to bottom. Moreover, each item has a yes or no answer.

  • Did you spell the module name correctly, including case?
  • Do the running Python and pip belong to the same interpreter?
  • Is the virtual environment active?
  • Do the editor and notebook use the same environment?
  • Does the install name match the import name?
  • Does a file in the folder share the module's name?
  • Do you run the code from the project root?
  • Is the requirements file for Docker or CI up to date?

We suggest printing the list and keeping it near your desk. ModuleNotFoundError usually returns for the same few reasons. Therefore, once the checklist becomes a habit, you solve the problem in minutes. If you need to read server logs, our free log file analyzer can help.

What information should you collect if the error persists?

If you ask someone for help, complete information speeds up the answer. The details below let a person diagnose the problem within minutes.

  1. Copy the full traceback without cutting it short.
  2. Write the command you ran and the folder you ran it from.
  3. Add the output of python -c "import sys; print(sys.executable)".
  4. Add the output of python -m pip --version.
  5. Say whether you use a virtual environment, Docker, CI or a notebook.
  6. Share a short tree view of the project folder.

Keep personal data out of this information. Before sharing, remove user names from paths and any secret keys. Also share only the smallest code that reproduces the error. For example, that makes reading easier and keeps secrets from leaking.

Do you want help setting up environment management for your project?

If the error is a one-off, the steps above are enough. However, if everyone on your team has a different machine, environment drift keeps costing time. In that case dependency management, setup scripts and deployment steps should be organized together.

For this kind of work, Talha Aslan and team offer custom software development. Describe your project and request a quote on our custom software development page. We define the scope together based on your project. We do not promise outcomes, but we run diagnosis and setup in an orderly sequence.

Frequently Asked Questions

Why does ModuleNotFoundError appear even after I ran pip install?
Because pip probably installed the package into a different Python than the one running your code. Several interpreters, an inactive virtual environment or another editor setting are the typical causes. Install with python -m pip install and confirm the running interpreter with the sys.executable output. These steps go in order.
What is the difference between python -m pip and plain pip?
The python -m pip form runs pip through the exact Python interpreter you call at that moment. Plain pip finds the first pip on your path, and that pip may belong to another Python. Therefore python -m pip guarantees that installing and running happen in the same environment.
What should I do if the error persists with the virtual environment active?
First confirm that the sys.executable output points to your environment folder. If it does, check with pip show that the package is installed there. Then make sure none of your own files shadows the module. If it still fails, delete the environment and recreate it from the requirements file.
Why does Jupyter raise ModuleNotFoundError when the terminal does not?
A Jupyter kernel is tied to its own Python installation, independent of the environment active in your terminal. So installing in one environment does not affect the notebook. Check sys.executable in the notebook, pick the right kernel, or use the percent pip install command inside the notebook, then restart the kernel.
Is setting PYTHONPATH a good solution?
Usually it should not be your first choice. PYTHONPATH depends on the machine, so it goes missing on another computer or in CI. A sturdier fix is to correct the project layout, run files as modules, and make the project an installable package if needed. Use PYTHONPATH only for a quick, temporary test.
How do I prevent this error in Docker?
Keep your dependencies in a requirements file and install from that file when you build the image. State the Python version explicitly in the image and run the install step before you copy the code. Set the working directory correctly. If you forget to add a new package to the file, code that works locally fails in the container.
  • python error
  • modulenotfounderror
  • no module named
  • pip install
  • virtual environment
  • python import
  • jupyter kernel
Share:
Talha Aslan

Google Partner digital marketing expert. Hands-on with SEO, Google Ads, web design and e-commerce projects since 2012; every post here comes from that experience.

Next project

Get a quote for your project.

Your brief goes straight to Talha Aslan and team: strategy led by Talha, delivery by an experienced team. We reply the same day and send the scope, timeline and price as a written quote within 1 business day.