ImportError
ImportError: cannot import name 'foo' from 'bar'
Traceback
Traceback (most recent call last):
File "main.py", line 1, in <module>
from collections import OrderedDic # typo
ImportError: cannot import name 'foo' from 'bar'What causes this error
Python found the module but could not import the requested name from it. This may be due to a typo, the name not existing in that module, circular imports, or version mismatches where the name was added or removed.
How to fix it
Verify the exact name exists in the module with `dir(module)`. Check the library version matches your code's expectations. For circular imports, restructure code or use late imports inside functions.
Code that causes this error
from collections import OrderedDic # typo
Fixed code
from collections import OrderedDict
About ImportError
An ImportError is raised when an import statement fails to find a module or cannot import a specific name from a module. This covers situations where a module exists but does not contain the requested attribute, when there are circular import dependencies, or when a package's `__init__.py` does not expose the expected names. ImportError is the parent class of ModuleNotFoundError (added in Python 3.6), which handles the case where the module itself does not exist.
When you see an ImportError (as opposed to ModuleNotFoundError), it usually means Python found the module but could not locate the specific name you requested. This might happen because the name was renamed or removed in a different version of the library, because of a typo in the import statement, or because of circular imports where module A imports from module B while module B imports from module A.
Common scenarios
Installing packages in a different virtual environment than the one in use
Circular imports between modules that depend on each other
Typos in module or package names in import statements
Naming a local file the same as a standard library module