Fix ImportError: cannot import name in Python

Quick Answer

ImportError: cannot import name means Python found the module but could not obtain the requested symbol from it. Check the spelling and exports, inspect module.__file__, look for a circular import, and make sure a local file is not shadowing the intended package.

Python ImportError cannot import name troubleshooting path symbol circular import and shadowing
Trace the failing import from the requested symbol to the loaded module, then check spelling, exports, circular dependencies, and module shadowing.

ImportError: cannot import name means Python found the module you asked for, but it could not find the specific name inside that module. The module import itself usually works; the failure happens when Python looks for a function, class, variable, or submodule that is missing, misspelled, not exported yet, or blocked by a circular import. For the Jinja2-specific removal of escape and Markup exports, Fix Cannot Import escape from Jinja2 maps compatible versions and modern imports.

The fastest fix is to check the imported name, then check the module that should define it. If the name exists but still fails, look for circular imports, file shadowing, wrong package versions, or imports that run before a name is created. The official Python ImportError documentation defines the exception, and the Python import system reference explains how imports are resolved.

Read the traceback from the bottom upward. The last line names the missing import, while the earlier lines show which file triggered it. That file path usually tells you whether the problem is in your project code, a local file that shadows a package, or a third-party dependency.

Check the Imported Name

Start with the simplest cause: the name does not exist in the module or is spelled differently. Python is case-sensitive, so User and user are different names.

# helpers.py
class User:
    pass


# main.py
from helpers import User

print(User)

If your code says from helpers import Users, Python will raise an ImportError because Users is not defined. Open the module and verify the exact spelling before changing package paths or reinstalling anything. Also check whether the name was renamed during a refactor.

Python Pool infographic showing module, requested name, import statement, package contents, and traceback
The module was found, but the requested name was not available from it at import time.

Confirm the Name Is Exported

If a module uses __all__, wildcard imports only expose the names listed there. Direct imports still depend on the name being defined in the module.

# tools.py
__all__ = ["slugify"]


def slugify(text):
    return text.lower().replace(" ", "-")


# app.py
from tools import slugify

print(slugify("Python Pool"))

For public package APIs, confirm that the name is actually part of the module you are importing from. Some libraries expose objects from a different submodule than examples suggest. A related guide on Python __all__ explains how explicit exports affect import behavior.

Fix Circular Imports

A circular import happens when two modules import each other while Python is still initializing them. The second module may ask for a name before the first module has finished defining it.

# users.py
from emails import send_welcome_email


class User:
    pass


# emails.py
from users import User


def send_welcome_email(user: User):
    print("welcome")

Break the cycle by moving shared code to a third module, importing inside a function, or redesigning the dependency direction. Circular imports are common when models, views, utilities, and app startup code all import each other. The dedicated Python circular import guide covers these patterns in more detail.

Python Pool infographic showing module A importing B, module B importing A, partial initialization, and error
Circular imports can expose a partially initialized module before the requested name exists.

Move Imports Inside Functions When Needed

A local import can be a practical fix when only one function needs the dependency and importing at module load time creates a cycle. It delays the import until the function is called.

def send_welcome_email(user_id):
    from users import get_user

    user = get_user(user_id)
    print(f"Welcome, {user.name}")

This is not a license to hide every import inside functions. Use it when it removes a circular dependency or avoids loading an optional dependency until it is needed. If many imports need to move inside functions, the module design probably needs a deeper cleanup. For broader patterns, see Python conditional imports.

Check for File Shadowing

Local files can shadow installed packages. If your project has a file named requests.py, flask.py, or PIL.py, Python may import that local file instead of the real package.

import importlib.util

spec = importlib.util.find_spec("json")

print(spec.origin)

This check prints where Python would import the module from. If the path points to the wrong file, rename the local file and remove any stale __pycache__ files. The official importlib documentation covers import inspection tools. File shadowing is especially easy to miss because the import name looks correct.

Use the Correct Package Version

Sometimes the name exists in one package version but not another. This is common after tutorials, package upgrades, or dependency conflicts. Check the installed version and compare it with the documentation for that version.

import importlib.metadata

package_name = "pip"
version = importlib.metadata.version(package_name)

print(version)

If a library moved or removed a name, update your import path or pin a compatible version. Avoid copying imports from old examples without checking the package’s current documentation. In team projects, confirm that your virtual environment matches the project’s lock file or requirements file. For the Pydantic-specific version and export changes behind MultiHostDsn import failures, continue with Fix cannot import name MultiHostDsn from Pydantic.

Python Pool infographic comparing definition, module path, __all__, import style, and available symbol
Confirm the name is defined in the module being imported and that the import style matches its API.

Best Practice

When you see ImportError: cannot import name, debug in this order: verify the exact name, confirm the module path, check for circular imports, look for local file shadowing, then check package versions. Keep imports at the top of the file unless a local import solves a real cycle or optional dependency problem. For more module organization examples, see Python modules, importing classes from another file, and importing from another directory.

After changing imports, run the file from the project root using the same environment your application uses. That prevents a fix from working in one terminal session but failing in your web server, notebook, test runner, or deployment process.

Read the Full ImportError Traceback

The final line identifies the requested name, but the earlier traceback lines show which file imported it and which module Python loaded. Reproduce the import in the same interpreter and inspect the module path.

import package_name

print(package_name.__file__)
print(hasattr(package_name, "expected_name"))

If the path points into your project when you expected site-packages, check for a file or directory with the same name. If the symbol is genuinely absent, inspect the package’s documented public API and version.

Python Pool infographic testing package path, spelling, shadowing file, versions, and validation
Check spelling, module path, local shadowing files, package versions, circular imports, and the full traceback.

Break Circular Imports

A circular import occurs when module A imports module B while B is still importing A. The requested symbol may not have been defined yet. Move shared constants or helpers into a small third module, or move a local import into the function that needs it when that is safe.

# common.py
DEFAULT_TIMEOUT = 10

# client.py
from .common import DEFAULT_TIMEOUT

Check for Shadowing and Stale Packages

Files such as requests.py, math.py, or a project directory named after a dependency can change import resolution. Rename the local shadowing path, remove stale bytecode if necessary, and run the check with the same virtual environment used by the application.

Frequently Asked Questions

What causes ImportError: cannot import name?

The module was found, but the requested symbol is absent, not exported yet, blocked by a circular import, or coming from a different module than expected.

How do I check which module Python imported?

Import the module and print module.__file__. The path reveals whether Python loaded the intended installed package or a local shadowing file.

How do I fix a circular import?

Move shared values into a third module, reduce top-level imports, or use a carefully scoped local import after the dependency has been initialized.

What is the difference between ImportError and ModuleNotFoundError?

ModuleNotFoundError usually means Python could not find the module at all, while ImportError can mean the module loaded but the requested name was unavailable.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted