[Solved] ImportError: Cannot Import Name

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

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:\Users\Rishav Raj\Documents\PythonPool\Circular Dependency\file2.py", line 1, in <module>
    from file1 import A
  File "C:\Users\Rishav Raj\Documents\PythonPool\Circular Dependency\file1.py", line 1, in <module>
    import file2
  File "C:\Users\Rishav Raj\Documents\PythonPool\Circular Dependency\file2.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:\Users\Rishav Raj\Documents\PythonPool\Circular Dependency\file1.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
class A:
    """Your Code"""
file2.py
class B:
    """Your Code"""
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_

import requests_oauthlib

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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments