I have two files app.py
and mod_login.py
app.py
from flask import Flask
from mod_login import mod_login
app = Flask(__name__)
app.config.update(
USERNAME='admin',
PASSWORD='default'
)
mod_login.py
# coding: utf8
from flask import Blueprint, render_template, redirect, session, url_for, request
from functools import wraps
from app import app
mod_login = Blueprint('mod_login', __name__, template_folder='templates')
And python return this error:
Traceback (most recent call last):
File "app.py", line 2, in <module>
from mod_login import mod_login
File "mod_login.py", line 5, in <module>
from app import app
File "app.py", line 2, in <module>
from mod_login import mod_login
ImportError: cannot import name mod_login
If I delete from app import app
, code will be work, but how I can get access to app.config
?
The Python ImportError: cannot import name
error occurs when an imported class is not accessible or is in a circular dependency.
What Causes ImportError: Cannot Import Name
This error generally occurs when a class cannot be imported due to one of the following reasons:
- The imported class is in a circular dependency.
- The imported class is unavailable or was not created.
- The imported class name is misspelled.
- The imported class from a module is misplaced.
- The imported class is unavailable in the Python library.
Python ImportError: Cannot Import Name Example
Here’s an example of a Python ImportError: cannot import name
thrown due to a circular dependency. Two python modules
test1.py
and test2.py
are created to achieve this:
test1.py:
from test2 import Class2
class Class1:
obj = Class2()
test2.py:
from test1 import Class1
class Class2:
obj = Class1()
In the above example, the initialization of obj
in test1
depends on test2
, and obj
in test2
depends on test1
. This is a circular dependency since both files attempt to load each other. Therefore, running test1.py
(or test2.py
) causes an ImportError: cannot import name
error:
Traceback (most recent call last):
File "test1.py", line 1, in
from test2 import Class2
File "test2.py", line 1, in
from test1 import Class1
File "test1.py", line 1, in
from test2 import Class2
ImportError: cannot import name 'Class2' from partially initialized module 'test2' (most likely due to a circular import) (test2.py)
How to Fix ImportError: Cannot Import Name in Python
The ImportError: cannot import name
can be fixed using the following approaches, depending on the cause of the error:
- If the error occurs due to a circular dependency, it can be resolved by moving the imported classes to a third file and importing them from this file.
- If the error occurs due to a misspelled name, the name of the class in the Python file should be verified and corrected.
- If the imported class is unavailable or not created, the file should be checked to ensure that the imported class exists in the file. If not, it should be created.
- If the imported class from a module is misplaced, it should be ensured that the class is imported from the correct module.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!
Hello Geeks! I hope all are doing great. So today, in this article, we will solve ImportError: Cannot Import Name. But, before that, we understand in which circumstances this error is raised and what are the main reasons for it and then will try to find possible solutions for them. So, Let’s get started.
ImportError occurs when a file cannot load the module, its classes, or methods in a python file. Now, there may be several reasons for this inability to load a module or its classes, such as;
- The imported module is not imported.
- The imported module is not created.
- Module or Class names are misspelled.
- Imported class is unavailable in certain library
- Or, the imported class is in circular dependency.
There may be more scenarios in which the importerror occurs. But in this article, we will only focus on the last one, i.e., The imported class is in a circular dependency.
To learn more about other reasons for the error, you can visit another article by us, i.e., Import-classes-from-another-file-in-python.
Circular Dependency
So, sometimes it happens that we imported two or modules in our file, and their existence depends on each other. In simples words, we can say that circular dependency is a condition in which two or more modules are interdependent. Now, when this happens, neither of the modules can successfully be imported, resulting in the given error. Let’s see an example to get a better understanding of it.
file1.py
from file2 import B class A: b_obj = B()
file2.py
from file1 import A class B: A_obj = A()
So, now in the above example, we can see that initialization of A_obj depends on file1, and initialization of B_obj depends on file2. Directly, neither of the files can be imported successfully, which leads to ImportError: Cannot Import Name. Let’s see the output of the above code.
Traceback (most recent call last):
File "C:UsersRishav RajDocumentsPythonPoolCircular Dependencyfile2.py", line 1, in <module>
from file1 import A
File "C:UsersRishav RajDocumentsPythonPoolCircular Dependencyfile1.py", line 1, in <module>
import file2
File "C:UsersRishav RajDocumentsPythonPoolCircular Dependencyfile2.py", line 1, in <module>
from file1 import A
ImportError: cannot import name 'A' from partially initialized module 'file1' (most likely due to a circular import) (C:UsersRishav RajDocumentsPythonPoolCircular Dependencyfile1.py)
Recommended Reading | Python Circular Import Problem and Solutions
Solving ImportError: Cannot Import Name
So, if you understood the core reason for the error, it is not difficult to solve the issue, and I guess most of you have already got the answer till now. Yes, the solution to this is that you can only avoid doing that. The above-given code results from a lousy programming approach, and one should avoid doing that. However, you can achieve your goal by maintaining a separate file for initializing the object.
file1.py
file2.py
file3.py
from file1 import A from file2 import B A_obj = A() B_obj = B()
Example 1: ImportError cannot import name in flask
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True)
Output:
Traceback (most recent call last):
File "test.py", line 1, in <module>
from flask import Flask
File "/home/pi/programs/flask.py", line 1, in <module>
from flask import Flask
ImportError: cannot import name Flask
The above-given error is raised as the flask is not installed in your system. To solve the error, you need to install it first and then import it. To install it, use the following command.
apt-get install python3-flask
Example 2: ImportError cannot import name in imagetk from pil
# create a class called Person # create init method # 2 attributes (name, and birthdate) # create an object from the Person class from PIL import Image, ImageTK import datetime import tkinter as tk # create frame window = tk.Tk() # create frame geometry window.geometry("400x400") # set title of frame window.title("Age Calculator App") # adding labels name_label = tk.Label(text="Name") name_label.grid(column=0, row=0) year_label = tk.Label(text="Year") year_label.grid(column = 0, row = 1) month_label = tk.Label(text="Month") month_label.grid(column = 0, row = 2) day_label = tk.Label(text="Day") day_label.grid(column = 0, row = 3) # adding entries name_entry = tk.Entry() name_entry.grid(column=1, row=0) year_entry = tk.Entry() year_entry.grid(column=1, row=1) month_entry = tk.Entry() month_entry.grid(column=1, row=2) day_entry = tk.Entry() day_entry.grid(column=1, row=3) def calculate_age(): year = int(year_entry.get()) month = int(month_entry.get()) day = int(day_entry.get()) name = name_entry.get() person = Person(name, datetime.date(year, month, day)) text_answer = tk.Text(master=window, wrap=tk.WORD, height=20, width=30) text_answer.grid(column= 1, row= 5) answer = "{name} is {age} years old!".format(name=person.name, age=person.age()) is_old_answer = " Wow you are getting old aren't you?" text_answer.insert(tk.END, answer) if person.age() >= 50: text_answer.insert(tk.END, is_old_answer) calculate_button = tk.Button(text="Calculate Age!", command=calculate_age) calculate_button.grid(column=1, row=4) class Person: def __init__(self, name, birthdate): self.name = name self.birthdate = birthdate def age(self): today = datetime.date.today() age = today.year - self.birthdate.year return age image = Image.open('LockVectorDaily.jpg') image.thumbnail((100, 100), Image.ANTIALIAS) photo = tk.PhotoImage(file=image) label_image = tk.Label(image=image) label_image.grid(column=1, row=0) window.mainloop()
Output:
from PIL import Image, ImageTK
ImportError: cannot import name 'ImageTK'
Here, the error occurs as Python is unable to import ImageTK. Now, the reason behind the error is unknown, but you can solve it by importing them separately using the following command.
import PIL
from PIL import TkImage
from PIL import Image
Example 3: Python ImportError: cannot import name _version_
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/requests_oauthlib/__init__.py", line 1, in
<module>
from .oauth1_auth import OAuth1
File "/usr/lib/python2.7/site-packages/requests_oauthlib/oauth1_auth.py", line 10, in
<module>
from requests.utils import to_native_string
File "/usr/lib/python2.7/site-packages/requests/utils.py", line 23, in <module>
from . import __version__
ImportError: cannot import name __version__
Check the __init__.py
at root dir. Openpyxl read this information from the .constrants.JSON file. However, PyInstaller somehow can’t make it right. I would you write a __version__.py
file by yourself and replace them in the __init__.py
.
import json import os # Modified to make it work in PyInstaller #try: # here = os.path.abspath(os.path.dirname(__file__)) # src_file = os.path.join(here, ".constants.json") # with open(src_file) as src: # constants = json.load(src) # __author__ = constants['__author__'] # __author_email__ = constants["__author_email__"] # __license__ = constants["__license__"] # __maintainer_email__ = constants["__maintainer_email__"] # __url__ = constants["__url__"] # __version__ = constants["__version__"] #except IOError: # # packaged # pass __author__ = 'See AUTHORS' __author_email__ = '[email protected]' __license__ = 'MIT/Expat' __maintainer_email__ = '[email protected]' __url__ = 'http://openpyxl.readthedocs.org' __version__ = '2.4.0-a1' """Imports for the openpyxl package.""" from openpyxl.compat.numbers import NUMPY, PANDAS from openpyxl.xml import LXML from openpyxl.workbook import Workbook from openpyxl.reader.excel import load_workbook print('You are using embedded openpyxl... 2.4.0-a1 ...')
Q1) How do you fix an importerror in Python?
It differs according to the mistake you have made.
All the possible solutions are discussed in the article refer it.
Q2) What is a name error in Python?
Name error is raised when the system cannot identify the variables used.
Conclusion
So, today in this article, we have seen the main reasons for ImportError: Cannot Import Name. We have seen the concept of circular dependency and how it affects our code. In the end, we have seen what things we should avoid getting into any such condition are.
I hope this article has helped you. Thank You.
Other Errors You Might Face
-
[Solved] typeerror: unsupported format string passed to list.__format__
●May 31, 2023
-
Solving ‘Remote End Closed Connection’ in Python!
by Namrata Gulati●May 31, 2023
-
[Fixed] io.unsupportedoperation: not Writable in Python
by Namrata Gulati●May 31, 2023
-
[Fixing] Invalid ISOformat Strings in Python!
by Namrata Gulati●May 31, 2023
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.
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.
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