Could not import module or member
Raised when the `import` statement has trouble loading a module, or when `from ... import` fails to find a name within a module. It's a general-purpose import failure.
- 1A circular dependency, where two modules try to import each other.
- 2Trying to import a specific name from a module, but that name does not exist in the module.
- 3The module is found, but there is an error during its initialization.
This error occurs when trying to import a specific function `non_existent_function` from the `math` module, where it does not exist.
from math import non_existent_function
expected output
Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name 'non_existent_function' from 'math'
Fix 1
Verify the name exists and check for typos
WHEN You get an error about a name that cannot be imported from a module.
# Incorrect: from math import non_existent_function # Correct: from math import factorial # 'factorial' is a real function in the math module
Why this works
Correcting the name to one that actually exists in the module's namespace allows the import to succeed.
Fix 2
Restructure code to avoid circular imports
WHEN Modules A and B import each other, causing a loop.
# In module_a.py
# from module_b import b_func -> This could cause a cycle if module_b imports module_a
# Refactored solution:
# Move shared dependencies to a third module, or import within a function.
def a_func():
from module_b import b_func # Local import to break the cycle
b_func()
Why this works
By moving the import statement inside a function, the import is delayed until the function is called, breaking the circular dependency at module load time.
from math import non_existent # ImportError: cannot import name
try:
from mylib import helper
except ImportError:
def helper(*args): return None # stub fallbackimport math
if hasattr(math, "factorial"):
from math import factorial✕ Modifying `sys.path` to fix import issues
While it can work, it makes your project's dependency structure implicit and brittle. It's better to structure your project as a proper package or use editable installs.
cpython/Python/import.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev