Import error python cannot import name

The python ImportError: cannot import name error occurs when the import class is inaccessible or the imported class in circular dependence. The import keyword is used to load class and function. The keyword from is used to load the module. For any reason, if the import class is not available in the python class path, The “ImportError: cannot import name” python error is thrown.

The python ImportError: cannot import name error occurs when the import class is inaccessible or the imported class in circular dependence. The import keyword is used to load class and function. The keyword from is used to load the module. For any reason, if the import class is not available in the python class path, The “ImportError: cannot import name” python error is thrown.

The following are the reasons for the ImportError: cannot import name

  • The import class is not available or not created.
  • The import class name is mis-named or mis-spelled
  • The import class name and module name is mis-placed.
  • The import class is not available in python class path
  • The import class is not available in python library
  • The import class is in circular dependency

The python module is just a python file with the .py extension. The keyword from will be used to load the python module. A class in a python module is imported using the keyword import. If the imported class is not in the referred python file, the python interpreter will throw the error ImportError: Cannot import name.

If two python files refer to each other and attempt to load the other file, it will create the circular load dependence. That will cause error in heap memory. If the python interpreter detects the circular dependence, it throws the error ImportError: Can’t Import Name.

Exception

The python interpreter will display the import error similar to the following

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 1, in <module>
    from Student import Student
ImportError: cannot import name Student
[Finished in 0.1s with exit code 1]

Root Cause

The python interpreter tries to locate and load the class specified in import statement. If the class name is inaccessible or unavailable, then this error will be thrown. There are numerous reasons for failing to locate or load the class. If the import class is available and loaded, it will fix this problem.

The other reason is that the load dependence is circular. If two python files refer to each other and try to load the other file, then the circular load dependency will be established. That will cause heap memory error. Python detects and throws the error ImportError: Can’t Import Name.

How to reproduce this issue

The error “ImportError: cannot import name” can be reproduced if you add a class name in the import statement that does not exist. The python interpreter will search for the class name in the python module. The class definition is not available in the python file. Therefore, python interpreter is going to throw this error.

In the example below, the Student.py file includes an Employee Class. The test.py file will import a student class from the student.py file. As the student.py file does not contain the student class, the python interpreter will throw this import error.

Student.py

class Employee:
	id = 1

test.py

from Student import Student

st = Student();
print(st.id);

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 1, in <module>
    from Student import Student
ImportError: cannot import name Student
[Finished in 0.1s with exit code 1]

Solution 1

The imported class will not be created or available in the python file. Check the import class in the python file. If this is not available, create a class in the python file. The python interpreter loads the class from the python file. This will resolve the “ImportError: Can not Import Name” error.

Student.py

class Student:
	id = 1

test.py

from Student import Student

st = Student();
print(st.id);

Output

1

Solution 2

The name of the import class may not be correct in the import statement. Verify the name of the class in the python file, correct the name of the class in the import statement. This could be due to spelling incorrectly in the import statement. Make sure the name of the class in the python file and the name of the class in the import statement are the same. This is going to fix the error.

Student.py

class Employee:
	id = 1

test.py

from Student import Employee

emp = Employee();
print(emp.id);

Output

1

Solution 3

The import class may not be available in the class you are looking for. The import class can be declared in a python file. The import statement can be searched in another python file. Verify the name of the module declared in the “from” keyword. The name of the module and the name of the python file must be the same. If different, either change the name of the file or change the name of the module.

Employee.py

class Employee:
	id = 1

Student.py

class Student:
	id = 1

test.py

from Student import Employee

emp = Employee();
print(emp.id);

Exception

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 1, in <module>
    from Student import Employee
ImportError: cannot import name Employee
[Finished in 0.1s with exit code 1]

Solution – test.py

from Employee import Employee

emp = Employee();
print(emp.id);

Solution 4

The common error is that the import class name and module name is mis-placed. In most of the time, the python class name and the python file name are same differs with camel case. If the class name and module name is misplaced in the import and from statement, then this error will occur.

employee.py

class Employee:
	id = 1

test.py – Error

from Employee import employee

emp = Employee();
print(emp.id);

The class name and module name is misplaced with Employee and employee. The correct import statement is as below

test.py – Solution

from employee import Employee

emp = Employee();
print(emp.id);

Solution 5

If two python files refer to each other and attempt to load the other file, it will create the circular load dependence. That will cause error in heap memory. If the python interpreter detects the circular dependence, it throws the error ImportError: Can’t Import Name.

Employee.py

from Student import Student
class Employee:
	id = 1

Student.py

from Employee import Employee
class Student:
	id = 1

In the above example Employee Module tries to load Student class and Student Module tries to load Employee class. This creates the circular dependency. Remove the circular dependency. This will resolve the import error.

[toc]

How to Fix : “ImportError: Cannot import name X” in Python?

Introduction

The import error might occur in numerous cases and scenarios. Some classic examples of import error have been explained in the following tutorials:

  • [Fixed] ImportError: No module named requests
  • How to Fix “ImportError: No module named pandas” [Mac/Linux/Windows/PyCharm]

In this article, you will learn about another import error that commonly occurs while you are dealing with packages and dependencies in Python.

A Quick Recap to Import Statement and ImportError

In Python, the import statement serves two main purposes:

  • It is used to search for the module specified by its name, then load and initialize it if the module is required.
  • It additionally defines a name in the local namespace within the scope of the import statement. This local name would then be able to be used to reference the accessed module throughout the whole code.

If an import statement experiences difficulty in successfully importing a module, it raises an ImportError.

Commonly, such an issue occurs because of a faulty installation or an invalid path, which will usually raise a ModuleNotFoundError in Python 3.6 and newer versions.

Problem Formulation

Let’s try understand the problem a bit better before we go into the solution!

In Python "ImportError: cannot import name" error generally occurs when the imported class is not accessible, or the imported class is in a circular dependency.

The following are the major reasons for the occurrence of "ImportError: cannot import name":

  • The imported class is in a circular dependency.
  • The imported class is not available or has not been created.
  • The imported class has been misspelled.
  • The imported class from a specific module is misplaced.
  • The imported class is not present in the Python library. This generally happens while importing external libraries.

Example: Consider you have two modules: x.py and y.py, as shown below.

These files represent how the ImportError occurs when there is a circular dependency between them, leading to a dead loop situation.

Let’s have a look at the contents of the first module:

x.py

from x import x_1


def y_1():
    print('y1')
    x_1()


def y_2():
    print('y2')


if __name__ == '__main__':
    y_1()

Let’s have a look at the contents of the second module:

y.py

from y import y_2


def x_1():
    print('x1')
    y_2()

Can you find the circular dependency?

Output:

ImportError: cannot import name 'x_1' from partially initialized module 'x' (most likely due to a circular import)

The error occurred because both the Python files, i.e., x and y, attempted to load each other simultaneously.

The y module tried to load the x module while the x module attempted to load the y module.

This created a circular load dependence leading to an error in the heap memory. To eliminate the ImportError, you have to get rid of the circular dependency.

Solution 1: Simply Use Import [Avoid from X import Y]

Simply put, the problem is occurring because we are trying to access the contents of one module from another simultaneously before the contents of the module are ready/initialized.

This happens particularly because you are using: from x import x_1 and from y import y_2.

Python can detect circular dependencies and prevent dead loops.

Essentially what happens is that an empty placeholder is created for the module (i.e., it does not contain any content).

After the modules that are circularly dependent are compiled, Python automatically updates the imported module. 

However, for Python to resolve the problem of circular dependency, you must use import x only instead of importing a particular content of the module with the help of the from statement.

As you are no longer trying to load the individual contents of the module at the top level, Python gets ample time to compile the module, thereby handling the circular dependency by itself.

Let’s have a look at the following code to understand how this works:

x.py

import x


def y_1():
    print('y1')
    x.x_1()


def y_2():
    print('y2')


if __name__ == '__main__':
    y_1()

And on to the second module!

y.py

import y


def x_1():
    print('x1')
    y.y_2()

Now, does it work or does Python raise a circular dependency error?

Output:

y1
x1
y2

Yes, it works!

Solution 2: Re-Order Position Of Import Statement

In the above example, you can avoid the circular dependency by reformating the sequence of import statements.

Thus, instead of importing the y module at the beginning within the x module, you can import it later, as shown in the following snippet:

x.py

def x_1():
    print('x1')
    y_2()


from y import y_2

Output:

y1
x1
y2

Conclusion

To sum things up, you can solve the “ImportError: Cannot import name X” Error by resolving the circular dependencies.

You can do that either by eliminating the usage of from x import y form of importing contents from a module and simply using the import statement to import the entire module.

Another workaround to this error is to change the position of the import statements accordingly within your code.

I hope this tutorial answered your queries. Please stay tuned and subscribe for more solutions and interesting discussions in the future. Happy coding!

Programmer Humor

Question: How did the programmer die in the shower? ☠️

Answer: They read the shampoo bottle instructions:
Lather. Rinse. Repeat.


Recommended Course:

  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.

shubham finxter profile image

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.

You can contact me @:

UpWork
LinkedIn

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 y.py file with the following code.

from x import x1

def y1():
 print('y1')
 x1()

def y2():
 print('y2')

if __name__ == '__main__':
 y1()

This file uses the function imported from the x.py file.

Now, let’s define the x.py file.

from y import y2

def x1():
  print('x1')
  y2()

Now, this file x.py is dependent on y.py. So that means the x.py file is dependent on y.py. 

You can see the circular dependencies.

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

Traceback (most recent call last):
 File "/Users/krunal/Desktop/code/pyt/database/y.py", line 1, in <module>
 from x import x1
 File "/Users/krunal/Desktop/code/pyt/database/x.py", line 1, in <module>
 from y import y2
 File "/Users/krunal/Desktop/code/pyt/database/y.py", 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/x.py)

And we get the following error.

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

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

def x1():
 print('x1')
 y2()

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. Cause of the ImportError: cannot import name Error in Python
  2. Fix the ImportError: cannot import name Error in Python

Fix the ImportError: Cannot Import Name in Python

With this explanation, we will learn why we get an error that is ImportError: cannot import name. We will also learn how to fix this kind of error in Python.

Cause of the ImportError: cannot import name Error in Python

We can use a couple of ways to fix this error, but before diving into the ways of fixing this error, let’s try to understand why this error occurs and when the ImportError generally occurs.

An ImportError in Python occurs if the import statement within your code experiences difficulty in successfully importing a module.

Such an issue commonly occurs because of a faulty installation of an external library or an invalid path to the module you are trying to import.

The question is raised: when does the ImportError: cannot import name (xyz) happen? This kind of ImportError generally occurs when the class you are trying to import is in a circular dependency.

What does that mean? What is a circular dependency? Circular dependency generally occurs when two modules try to import each other simultaneously such that both of them are dependent on each other.

To further explain this, we need to look at an example to understand how and when this error occurs. Let’s say we have a couple of modules: demo1.py and demo2.py.

Before moving into the import statements, let’s look at the contents of these modules and then at the import statements.

As we can see, the demo2 module has a couple of functions: demo2_func1() and demo2_func2(). Similarly, the demo1 module has a single function called demo1_func1().

As we can see, within the demo2 module, we are importing demo1_func1 from the module demo1. Similarly, within the demo1 module, we are trying to import the function called demo2_func2(), which is a part of the demo2 module.

Python ImportError Cannot Import Name Example

Let’s focus on the demo2 module.

We can see that the demo2_func1() function prints some string and then loads the demo1_func1() function, which we have imported from the demo1 module. When the demo1_func1() calls, it will print some string.

In the next line, within the demo1_func1() function, we call the demo2_func2() method, so we can see the demo2_func2() method is also part of the demo1 module. We can see both these modules are interdependent.

In this case, when we use a statement like from demo1 import demo1_func1 and from demo2 import demo2_func2, a circular dependency occurs.

If we execute the demo2 module, then the expected output should be something like this since demo2_func1() is being called initially, then we move on to the demo1_func1() function and so on. After execution, we have an ImportError that says (cannot import name 'demo1_func1').

ImportError: cannot import name 'demo1_func1' from partially initialized module 'demo1' (most likely
due to a circular import)

This majorly occurs because we are trying to access the contents of one module from another and vice versa. If we look at the demo2.py module, we try to import the demo1_func1 function from demo1 before demo1_func1 was initialized; that is when the program begins.

Python is still initializing the contents of the demo1 module, but we are not giving ample time to Python to initialize the demo1_func1 function. We are directly calling it, which is why we encountered this ImportError.

Fix the ImportError: cannot import name Error in Python

Now we will see how we can fix this error. We can fix this error in two ways, but we will use the easiest way: to avoid the circular dependency, and Python can do it by itself.

To resolve the problem, we must make certain code changes.

We have to modify the import statement, and instead of importing the module’s contents, we import the entire module in both files.

The source code of the demo1.py file:

import demo2

def demo1_func1():
    print('demo1_func1')
    demo2.demo2_func2()

The code of the demo2.py file:

import demo1

def demo2_func1():
    print('demo2_func1')
    demo1.demo1_func1()


def demo2_func2():
    print('demo2_func2')


if __name__=='__main__':
    demo2_func1()

Output:

demo2_func1
demo1_func1
demo2_func2

Mostly this error occurs when we are developing the Flask app using the blueprint approach, so if you are creating a Flask structure, you may need to follow this link.

Понравилась статья? Поделить с друзьями:
  • Import could not be resolved python как исправить
  • Implicit conversion from number to string как исправить
  • Imperial glory вылетает после боя как исправить
  • Imperator rome ошибка 0xc0000142
  • Impedance error edge core