Python ImportError: cannot import name
The module exists but the specific name (function, class) cannot be imported from it.
Explanation
This specific form of ImportError occurs when the module is found but the requested name doesn't exist within it. For example, from os import nonexistent_function will raise this error. Common causes include typos in the imported name, the name being in a different submodule, version differences where the API changed, or the name having been renamed in a newer version of the library. This is one of the most common import errors in Python.
Common Causes
- Name doesn't exist in the module
- Typo in imported name
- Library version API change
- Name moved to submodule
- Name is private (underscore prefix)
Solution
Check the library documentation for the correct import name. Verify the library version matches the documentation you're following. Use dir(module_name) to list available names in the module. Check if the name is in a submodule that needs separate import. Try importing the module first and then accessing the name with dot notation. Consider using from module import * temporarily to see all available names.
Code Example
# Wrong name from correct module
from collections import OrderedDict # works in older Python
from collections import ChainMap # works
from collections import Hashable # ImportError in Python 3.10+!
# Fix: in Python 3.10+, use collections.abc
from collections.abc import Hashable
# Version-specific API changes
from flask import Flask # always works
from flask import json_encoder # removed in Flask 2.2+
# Fix: use the new API
from flask.json.provider import DefaultJSONProvider
# Check available names
import collections
print(dir(collections)) # see all exports
# Typo in name
from datetime import datatime # ImportError: cannot import name 'datatime'
# Fix
from datetime import datetime
Error Information
Language
python
Difficulty
Beginner
Views
14
Related Errors
Python
Python TabError
The code uses inconsistent indentation by mixing tabs and spaces.
Python
Python SyntaxError
Python detected invalid syntax in the source code.
Python
Python RecursionError
The function calls itself too many times, exceeding the maximum recursion depth.
Python
Python FileNotFoundError
The code tries to open or access a file or directory that does not exist.