ImportError: cannot import name ‘xyz’

Loading

The error message:

ImportError: cannot import name 'xyz' from 'module_name'

occurs when Python fails to import a specific function, class, or variable from a module.


1. Causes and Solutions

Cause 1: The Function/Class Does Not Exist in the Module

If the function or class you are trying to import does not exist in the module, Python will raise an ImportError.

Incorrect Code:

from math import sine  # 'sine' does not exist in the math module

Error Output:

ImportError: cannot import name 'sine' from 'math'

Solution: Use the Correct Function Name

from math import sin  # 'sin' is the correct function name

Cause 2: Circular Import

A circular import happens when two or more modules depend on each other, causing an import loop.

Example:

file1.py

from file2 import func2  # Imports from file2.py
def func1():
print("Function 1")

file2.py

from file1 import func1  # Imports from file1.py (circular import!)
def func2():
print("Function 2")

Error Output:

ImportError: cannot import name 'func1' from 'file1'

Solution: Delay the Import or Use Import Inside the Function

Modify file2.py to import inside a function:

def func2():
from file1 import func1 # Import inside function
func1()
print("Function 2")

Cause 3: Importing from the Wrong Module

Sometimes, you may try to import an object from the wrong module.

Incorrect Code:

from numpy import dataframe  # 'dataframe' is not in numpy

Solution: Import from the Correct Module

from pandas import DataFrame  # 'DataFrame' is in pandas

Cause 4: Importing from a Script with the Same Name as a Module

If you name your script the same as a built-in module, Python may import your script instead of the actual module.

Incorrect Scenario:

  • Your script is named random.py, and you try: pythonCopyEditfrom random import randint
  • Python imports your random.py, not the built-in one.

Solution: Rename Your Script

  • Rename random.py to random_utils.py
  • Delete __pycache__ folders.

Cause 5: Module Not Properly Installed

If you are importing from an external package that is not installed, you will get an import error.

Incorrect Code:

from requests import request  # If requests module is missing

Solution: Install the Required Module

pip install requests

2. Best Practices to Avoid ImportError

Ensure the function/class exists in the module
Avoid circular imports by restructuring imports
Use the correct module for the import
Avoid naming scripts the same as built-in modules
Use pip install module_name to install missing modules

Leave a Reply

Your email address will not be published. Required fields are marked *