ImportError

ImportError is a built-in exception that occurs when an import statement doesn’t successfully load a module or a name from a module.

This exception is part of Python’s import system, which is responsible for loading and managing modules.

You should handle ImportError when your code depends on external modules or packages that may not be available in the execution environment.

ImportError Occurs When

  • Importing a module that’s not installed or not available in your current environment
  • Trying to import a specific name from a module when the name doesn’t exist

ImportError Can Be Used When

Handling optional dependencies in your code by providing alternative implementations or fallbacks.

Optional Attributes

ImportError provides two optional attributes that you can access when handling the exception:

  • name: The name of the module that couldn’t be imported.
  • path: The file path Python tried to load. It’s None if there’s no physical file, if the module is built in, or if the name doesn’t exist in an already loaded module.

Examples

An example of when the exception appears:

Python
>>> from math import non_existing_name
Traceback (most recent call last):
    ...
ImportError: cannot import name 'non_existing_name' from 'math'

An example of how to handle the exception:

Python
>>> try:
...     from math import non_existing_name
... except ImportError:
...     print("The name 'non_existing_name' doesn't exist in 'math'.")
...
The name 'non_existing_name' doesn't exist in 'math'.

Below is another example that shows how you can use the .name and .path attributes:

Python
>>> try:
...     import some_non_existent_module
... except ImportError as e:
...     print("An ImportError occurred.")
...     print(f"Name: {e.name}")
...     print(f"Path: {e.path}")
...
An ImportError occurred.
Name: some_non_existent_module
Path: None

Tutorial

Python import: Advanced Techniques and Tips

The Python import system is as powerful as it is useful. In this in-depth tutorial, you'll learn how to harness this power to improve the structure and maintainability of your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 13, 2025 • Reviewed by Martin Breuss