ImportError: cannot import name '...'
ImportError: cannot import name '...' means the module was found, but the specific name you’re trying to import doesn’t exist or isn’t exported by that module.
What It Means
Python successfully located the module file but couldn’t find the requested class, function, or variable inside it. This is different from ModuleNotFoundError — the module exists, but the name doesn’t.
Why It Happens
- The name doesn’t exist in that module (typo or removed in a newer version)
- Version mismatch — a function was renamed, moved, or deprecated
- Circular imports where one module tries to import from another before the name is defined
- The name is defined inside an
if __name__ == "__main__"block and isn’t available for import - A spelling mistake in the import statement
How to Fix It
Step 1: Verify the name exists
Check the module’s public API:
import <module>
print(dir(<module>))Or check the documentation to confirm the correct import path.
Step 2: Check the module version
If an API changed between versions:
pip show <module>
# Check the version, then install the right one:
pip install <module>==<known-working-version>Step 3: Fix circular imports
If module A imports from B, and B imports from A, restructure the code:
# Instead of importing at the top of the file, import inside the function
def my_function():
from some_module import SomeClass
return SomeClass()Or move the shared code to a third module.
Step 4: Avoid importing from __main__ guards
Don’t try to import names defined inside if __name__ == "__main__":
# BAD — main.py
if __name__ == "__main__":
my_var = 42
# GOOD — move the definition outside the guard
my_var = 42
if __name__ == "__main__":
passStep 5: Check for name shadowing
Make sure your file doesn’t shadow the module you’re importing from:
# If you name your file os.py, this will fail:
import os # imports your file, not the standard library
print(os.getcwd()) # AttributeError: module 'os' has no attribute 'getcwd'Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro