How to Fix ImportError: cannot import name in Python

The ImportError: cannot import name error occurs in Python when the imported class is in a circular dependency or the imported class is unavailable or was not created.

To fix ImportError: cannot import name in Python, solve the circular dependencies, and defer imports. To fix the circular dependencies, we can use the module in a function when we need it.

Breaking a circular dependency makes the code cleaner and more understandable and gives easy access to all methods requiring dependency.

Python implements at least three different ways to import modules. You can use the import statement, the from statement, or the built-in __import__ function.

Modules are performed during import, and new functions and classes won’t see in the module’s namespace until the def (or class) statement has been executed.

Code Snippet

See the below snippet, which eliminates the circular dependencies.

import WhateverModule

def WhateverFunction(arg):
  from some.dependency import DependentClass

Python can detect circular dependencies and prevent the infinite loop of imports. What happens is that an empty placeholder is created for the module.

Once the circularly dependent modules are compiled, it updates the imported module.

Making logic clear is very important. This problem appears because the reference becomes a dead loop. Let’s take an example of circular dependencies.

Let’s define a file with the following code.

from x import x1

def y1():

def y2():

if __name__ == '__main__':

This file uses the function imported from the file.

Now, let’s define the file.

from y import y2

def x1():

Now, this file is dependent on So that means the file is dependent on 

You can see the circular dependencies.

Finally, if you run the file file, you can see the following code.

Traceback (most recent call last):
 File "/Users/krunal/Desktop/code/pyt/database/", line 1, in <module>
 from x import x1
 File "/Users/krunal/Desktop/code/pyt/database/", line 1, in <module>
 from y import y2
 File "/Users/krunal/Desktop/code/pyt/database/", line 1, in <module>
 from x import x1
ImportError: cannot import name 'x1' from partially initialized module 'x' 
(most likely due to a circular import) (/Users/krunal/Desktop/code/pyt/database/

And we get the following error.

ImportError: cannot import name ‘x1’ from partially initialized module ‘x’.

To fix the ImportError, modify the file. For example, instead of importing the y module at the start of the file, write at the end of the file.

def x1():

from y import y2

Now rerun, and you can see the following output.


We have solved this problem by using the import module or class or function where we needed it. If we use this approach, we can fix circular dependency.

That is it.

1 thought on “How to Fix ImportError: cannot import name in Python”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.