Ошибка python importerror cannot import name

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__

    [Solved] typeerror: unsupported format string passed to list.__format__

    May 31, 2023

  • Solving ‘Remote End Closed Connection’ in Python!

    Solving ‘Remote End Closed Connection’ in Python!

    by Namrata GulatiMay 31, 2023

  • [Fixed] io.unsupportedoperation: not Writable in Python

    [Fixed] io.unsupportedoperation: not Writable in Python

    by Namrata GulatiMay 31, 2023

  • [Fixing] Invalid ISOformat Strings in Python!

    [Fixing] Invalid ISOformat Strings in Python!

    by Namrata GulatiMay 31, 2023

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

ImportError occurs when Python is unable to load an attribute (class, method, or variable) from a module. The following are common reasons why that happens:

  • The imported attribute does not exist or is misspelled,
  • There is a circular dependency between the script being executed and the module is loaded,
  • The imported attribute is not available in the Python library of packages, and,
  • Naming scripts after installed modules

In the coming sections, we will discuss these causes and provide a solution for each case.

The imported attribute does not exist or is misspelled

In this case, the function/class/variable we are trying to load does not exist. This can arise when we misspell the attribute we intend to import, or it is just not created. For example, suppose we have two scripts, executing_script.py, and math2.py, in the same folder. We intend to run executing_scipt.py to call some functions in math2.py.

File:math2.py

from numpy import exp

#from numpy module we import exp, the Euler’s number, e,

# exp(1)=e^1 is approximately 2.7182…

def discount(rate, price):

    return rate*price +exp(rate)

def discounted_price(rate, price):

    return (1rate)*price exp(rate)

In the executing_script.py script, we intend to import and use the discounted_price() function from math2.py.

File: executing_script.py

from math2 import discount_price

discount_price(0.1, 980)

Output (running executing_script.py):

ImportError: cannot import name 'discount_price' from 'math2'

We misspelled the function, hence the error.

Solution

To fix the ImportError of this kind, we need to ensure that the attribute(s) we are importing exists. In the case above, we needed to import the discounted_price() function, not discount_price, as follows

File: executing_script.py

from math2 import discounted_price

print(discounted_price(0.1, 980))

Output:

880.8948290819244

Remember that we can also import the module math2.py and access its attributes as follows.

import math2

print(math2.discounted_price(0.1, 980))

Or, import all the attributes in the math2 module and use them as follows

# import all attributes on the math2 module

from math2 import *

marked_price = 645

rate = 0.1 #10 percent discount

print(«Marked Price:», marked_price)

print(«Discounted price:», discounted_price(0.1, marked_price))

print(«The discount amount:», discount(0.1, marked_price))

Output:

Marked Price: 645
Discounted price: 579.3948290819244
The discount amount: 65.60517091807564

The imported attribute is not available in the Python library

The ImportError resulting here is the same as discussed in the first section. The only difference is that the library being loaded here is not user-defined (it is Python packages that come preinstalled or installed by pip).

For example, suppose we want to convert a Python list into a NumPy array using the NumPy package.

from numpy import arr

lst1 = [1, 4, 5, 6]

arr1 = arr(lst1)

Output:

ImportError: cannot import name 'arr' from 'numpy'

NumPy module does not have a function arr and therefore cannot be imported. What we are looking for, instead, is the “array” function.

from numpy import array

lst1 = [1, 4, 5, 6]

arr1 = array(lst1)

By importing the correct method, the error is fixed. As said earlier, you can also load the module and access the attribute it contains as follows. If the module is unavailable, as shown below, we run into another class of error AttributeError.

import numpy as np

lst1 = [1, 4, 5, 6]

arr1 = np.arr(lst1)

Output:

AttributeError: module 'numpy' has no attribute 'arr'

The error explains it well; the “arr” attribute is not in numpy.

Circular Dependency

Circular dependency imports occur when two scripts are interdependent – the script being executed (script A) imports attribute(s) from the second script (script B), which also calls some attributes on the script being executed (script A).

Figure 1: A circular dependency import (Source: Author).

This circular dependency occurs because the module loading process cannot be completed. To understand why this is so, let us see an example.

File: physics1.py

from math1 import multiply

def acceleration(u, v, t):

    return (u*v)/t

def mc(m, c):

    return m*(c**2)

a = multiply(9, 10)

print(a)

File: math1.py

from physics1 import acceleration, mc

def multiply(a, b):

    return a*b

acc = acceleration(2, 8, 2)

print(acc)

E = mc(4, 2.4)

print(E)

When we execute the math1.py script, we run into ImportError with the description below:

ImportError: cannot import name ‘acceleration’ from partially initialized module ‘physics1’ (most likely due to a circular import)

Python detected a circular import and stopped the execution. The attempt to import modules in this manner can run indefinitely because the module will be partially initialized at every import — because of using from A import attr1.

The script math1.py tries to import acceleration() and mc() in physics1, and even before that is done, physics1.py also tries to import an attribute in math1.py.

There are different ways to solve this. We will discuss two in this article.

Solution 1: Defer the importation

When we run math1.py, we import two functions: acceleration and mc. Circular dependency arises because before these methods are imported, physics1.py is also trying to import from math1.py. To fix this problem, we can import functions on math1.py after importing the two functions.

File: physics1.py

def acceleration(u, v, t):

    return (u*v)/t

def mc(m, c):

    return m*(c**2)

# put the attributes that cause circular dependency before the import statement

from math1 import multiply

a = multiply(9, 10)

print(a)

File: math1.py

from physics1 import acceleration, mc

def multiply(a, b):

    return a*b

acc = acceleration(2, 8, 2)

print(acc)

E = mc(4, 2.4)

print(E)

Output (when we execute math1.py):

8.0
23.04
90
8.0
23.04

Note: When attributes are imported, the entire module is scanned. That is why the acceleration() and mc() function prints the output on executing math1.py and also on the import line in physics1.py (from math1 import multiply).

Solution 2: Transfer attributes to a third file

This is probably the best way to deal with circular imports because it gives us a clean code (according to PEP standards it is a good idea to keep imports at the top of the file), and it is straightforward and also efficient.

In this case, we will take all the functions into a script named “third.py” and call them from that central point.

File: third.py

def multiply(a, b):

    return a*b

def acceleration(u, v, t):

    return (u*v)/t

def mc(m, c):

    return m*(c**2)

File: math3.py

from third import acceleration, mc, multiply

acc = acceleration(2, 8, 2)

print(acc)

E = mc(4, 2.4)

print(E)

a = multiply(9, 10)

print(a)

Output:

8.0
23.04
90

Naming scripts after installed modules

When naming Python scripts, we should avoid giving them names matching the installed packages. This is because if we try importing a user-defined module with a name similar to an installed package Python will throw an ImportError. Let’s see an example.

In this example, we have two scripts named math.py and script1.py in the same directory.

File: math.py

def add2(a, b):

    return a + b

File: script1.py

from math import add2

print(add2(9, 8))

On executing script1.py, we get the following error message:

ImportError: cannot import name 'add2' from 'math' (unknown location)

When importing modules, Python looks for these packages in specific places – among them is the current working directory and the default package location created during Python installation.

In our current directory, we have a user-defined module named math when we are executing script1.py. There exists also a preinstalled package called math. In this case, therefore, Python loads the preinstalled math and does not see the math.py script in our current working directory.

The error in this category can be solved by simply avoiding the use of names matching the installed packages for our user-defined modules.

Conclusion

ImportError occurs because Python is unable to import the attributes we are trying to load. This can happen because of several reasons.

Firstly, the imported attribute might not exist or has been misspelled. In this case, you need to countercheck the names of the attributes you are trying to import.

Secondly, we can run into circular dependence during importation. This happens when two scripts are trying to import each other.

We discussed two solutions for this problem and alluded that the best one is to move functions into a single file and import them from there.

Lastly, we covered an ImportError related to how we name our user-defined modules. If we give a name that matches the installed package to our user-defined modules, Python may default to incorrectly loading system-wide packages.

  • Ошибка pycharm failed to load jvm dll
  • Ошибка pxe mof exiting pxe rom на ноутбуке msi
  • Ошибка pxe m0f exiting pxe rom
  • Ошибка pxe e61 на ноутбуке
  • Ошибка pxe e61 как исправить