Skip to content
ImportError: cannot import name '...'

ImportError: cannot import name '...'

DodaTech 2 min read

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__":
    pass

Step 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'
How do I see all available names in a module?
Use dir(module_name) in a Python REPL. For third-party packages, check the official documentation or run python -c "import module_name; print(dir(module_name))".
What is the most common cause of ImportError?
Version mismatch tops the list. Packages like Pandas, Django, or Flask rename or move functions between major versions. Always pin your dependencies with pip freeze > requirements.txt to avoid surprises.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro