Latest Code Tutorials

Python cannot import name: How to Solve ImportError


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.

Python cannot import name

To solve ImportError: cannot import name in Python, solve the circular dependencies, and defer imports. To solve circular dependencies, use the module in a function when we needed it. Breaking a circular dependency makes the code cleaner, understandable and gives easy access to all methods requiring dependency.

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. Basically, what happens is that an empty placeholder is created for the module. Once the circularly dependent modules are compiled, it updates the imported module.

To make 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 is using the function imported from the file.

Now, let’s define the file.

from y import y2

def x1():

Now, this file is dependent on 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 resolve the ImportError: Cannot import name, modify the file. 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 resolving ImportError: Python cannot import name.

Leave A Reply

Your email address will not be published.

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