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’sNone
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:
>>> 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:
>>> 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:
>>> 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
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Absolute vs Relative Imports in Python (Tutorial)
- Python Exceptions: An Introduction (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Advanced Python import Techniques (Course)
- Python import: Advanced Techniques and Tips (Quiz)
- Absolute vs Relative Imports in Python (Course)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)