How to Fix ImportError in Python
In this tutorial, you'll learn about How to Fix ImportError in Python. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Error message: ImportError: cannot import name 'something' from 'module'
ImportError occurs when the import statement finds the module but can't find the specific name inside it. It's closely related to ModuleNotFoundError but more specific.
Cause 1: Circular Imports
Module A imports from B, and B imports from A:
# module_a.py
from module_b import func_b
def func_a():
return func_b()
# module_b.py
from module_a import func_a # Circular!
def func_b():
return "hello"
Fix: Restructure — move shared code to a third module, or use lazy imports inside functions:
# module_b.py
def func_b():
return "hello"
def func_a_wrapper():
from module_a import func_a # Lazy import — inside function body
return func_a()
Cause 2: Wrong Import Path
The name you're importing doesn't exist in that module, or the path is incorrect:
# Wrong — os.path is a module, not os file
from os import path # Works
from os import file # ImportError: cannot import name 'file' from 'os'
# Wrong submodule
from os.path import non_existent # ImportError
Fix: Check the module's contents:
python -c "import os; print(dir(os))"
Cause 3: Outdated Package
The name you're importing was renamed or removed in a newer version:
# Old: from collections import Mapping
# New (Python 3.10+):
from collections.abc import Mapping
Fix: Check the package's changelog or Migration guide:
pip show package_name
Cause 4: Relative Import Outside a Package
# Running: python my_script.py
from . import something # ImportError: attempted relative import with no known parent package
Fix: Use absolute imports, or run the script as a module:
python -m package.my_script
Cause 5: init.py Is Missing or Empty
In older Python versions (3.3-), a directory isn't recognized as a package without __init__.py:
# Directory structure:
# mypackage/
# __init__.py ← missing!
# utils.py
from mypackage import utils # ImportError
Fix: Add an empty __init__.py file to the directory:
touch mypackage/__init__.py
In Python 3.3+ (namespace packages), this isn't strictly required, but it's still best practice.
Prevention
- Avoid circular imports by designing modules with clear dependency direction
- Use
python -c "from module import name"to test imports before using them in code - Keep your packages updated with
pip list --outdated - Use
pip checkto verify consistent dependencies - Structure projects as proper packages with
__init__.py - Prefer absolute imports over relative imports
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro