Fix: ImportError: cannot import name 'X' from 'Y'
Exact message
ImportError: cannot import name 'foo' from 'mymodule'
Quick answer
ImportError: cannot import name X means Python found the module Y but could not find the name X inside it. The usual causes are a typo in the name, a circular import between two modules, or X is actually defined in a submodule.
Why this error happens
Python first locates the module Y on sys.path, then looks up X as an attribute of that module. If X is missing — because of a typo, a different case, a circular import that prevents full initialization, or X lives in a submodule — it raises ImportError.
Example: Wrong vs Right
Wrong
from mymodule import foo # ImportError: cannot import name 'foo' from 'mymodule'
Right
# Check: is foo actually defined in mymodule? # mymodule.py # def foo(): ... # Or if it is in a submodule: from mymodule.utils import foo # Or use the module-qualified form to catch missing attrs: import mymodule mymodule.foo()
How to fix it (step by step)
- Open the target module and confirm the name is spelled and cased exactly the same
- Check whether the name is defined in a submodule — then import from that submodule
- Look for circular imports: module A imports from B, and B imports from A
- Print the module's dir() at import time to see what is available
Frequently asked questions
How do I fix circular imports?
Move the shared code to a third module both can import, or defer the import inside a function so it happens at runtime instead of at module load.
Why does it work in one file but not another?
sys.path differs between files. A file in a subdirectory may not see the same top-level packages. Use absolute imports from the project root.
Does case matter?
Yes, on Linux and macOS case-sensitive filesystems. 'Foo' and 'foo' are different modules on Linux, unlike Windows.
Related Python errors
Need a fix for a different error?
Use the free to paste any traceback and get an AI-suggested fix in seconds.
Want an AI with memory for your project?
MonsterX AI remembers your codebase across chats.