The ImportError exception is raised when there is an import issue. It typically occurs when the resource being imported does not exist in the target module.

For example when two different modules are importing objects from each other, and there is a circular dependency on the objects, an ImportError is raised.

Consider the following two Python files:

file1.py

from file2 import Class2

class Class1:
   obj = Class2()

file2.py

from file1 import Class1

class Class2:
   obj = Class1()

Output: 

Traceback (most recent call last):
  File "C:\Users\John\Desktop\test1.py", line 1, in <module>
    from test2 import Class2
  File "C:\Users\John\Desktop\test2.py", line 1, in <module>
    from test1 import Class1
  File "C:\Users\John\Desktop\test1.py", line 1, in <module>
    from test2 import Class2
ImportError: cannot import name 'Class2' from partially initialized module 'test2' (most likely due to a circular import)

The above case is what is regarded as circular dependency as the objects being imported(Class1 and Class2) depend on each other. 

Causes of the ImportError exception

  • When there is a circular dependency in the object/class being imported.
  • The object being imported does not exist in the target module.
  • The object or class being imported is misspelled.
  • The imported class is unavailable in the standard library.
from math import power

Handling the ImportError exception

In the case where the exception is being caused by circular dependency on classes, you can move the classes causing the error on a separate file and then import them from the file.

The next obvious solution is to ensure that the object or classes being imported actually exists in the target file. Additionally, you should ensure that the names are correctly spelled.