ImportPython Error

ImportError

ImportError: cannot import name 'foo' from 'bar'

Traceback

terminal
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

The module was found but does not contain the requested name. Typos, version differences, circular imports, or incorrect package __init__.py are common causes.

How to fix it

Check the name spelling with `dir(module)`. Verify the library version matches your code. For circular imports, use late imports inside functions. Check the module's documentation for correct import paths.

Code that causes this error

Broken
from collections import OrderedDic  # typo

Fixed code

Fixed
from collections import OrderedDict

About ImportError

This ImportError occurs when Python finds the module but cannot find the specific name you are trying to import from it. This differs from ModuleNotFoundError in that the module itself loads successfully — it just does not contain the requested attribute. Common causes include typos in the imported name, the name existing in a different version of the library, circular imports where module loading order matters, and incorrect assumptions about what a package's `__init__.py` exports.

For circular imports, the module may only be partially loaded when the import is attempted, so names defined later in the file are not yet available. The error message includes both the name and the module, and Python 3.12+ provides 'Did you mean?' suggestions for similar names.

Common scenarios

1

Installing packages in a different virtual environment than the one in use

2

Circular imports between modules that depend on each other

3

Typos in module or package names in import statements

4

Naming a local file the same as a standard library module

Related errors