Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Solving "ImportError in Importing from Sklearn: Cannot Import Name Check_Build"
Next article icon

Importerror: Cannot Import Name In Python

Last Updated : 02 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

One common error that developers encounter is the "ImportError: Cannot Import Name." This error occurs when the Python interpreter is unable to import a particular name or module within your code. In this article, we'll explore what causes this error and provide solutions to fix it.

What is ImportError: Cannot Import Name?

The "ImportError: Cannot Import Name" error typically occurs when there is a circular import or a dependency loop in your Python code. Circular imports happen when two or more modules depend on each other, creating a loop that confuses the interpreter. As a result, Python raises an ImportError because it cannot determine the correct order of module imports.

Syntax:

Importerror: Cannot Import Name 

Why does Importerror: Cannot Import NameError Occurs?

Below, are the reason that's why Importerror: Cannot Import Name occurs in Python:

  • Circular Import
  • Incorrect Module Reference
  • Typo in Import Statement

Circular Import

Below, the code consists of two Python modules, `module_a.py` and `module_b.py`. `module_a` imports `function_b` from `module_b`, and `module_b` imports `function_a` from `module_a`, creating a circular dependency. This circular import structure can lead to the "ImportError: Cannot Import Name" when attempting to use functions from either module.

module_a.py

Python3
# module_a.py from module_b import function_b  def function_a():     print("Function A") 

module_b.py

Python3
# module_b.py from module_a import function_a  def function_b():     print("Function B") 

Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 2, in <module>
from module_b import function_b
Importerror: No module named 'module_b'

Incorrect Module Reference

In below, code `main.py` attempts to import `my_function` from `mymodule`, but `mymodule.py` defines a function named `another_function`. This inconsistency causes an `ImportError: Cannot Import Name` when calling `my_function()` in `main.py`.

main.py

Python3
# main.py from mymodule import my_function  my_function() 

mymodule.py

Python3
# mymodule.py def another_function():     print(&quot;Another Function&quot;) 

Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 2, in <module>
from mymodule import my_function
Importerror: No module named 'mymodule'

Typo in Import Statement

In `myscript.py`, an attempt to import and execute `my_function` from `utils` causes an `ImportError: Cannot Import Name` because the function is defined later in `utils.py`. To resolve, switch the order of the import statement and function definition in `utils.py`.

myscript.py

Python3
# myscript.py from utils import my_function  my_function() 

utils.py

Python3
# utils.py def my_function():     print(&quot;My Function&quot;) 

Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 2, in <module>
from utils import my_function
Importerror: No module named 'utils'

Solve Importerror: Cannot Import Name In Python

Below, are the three approaches to solve Importerror: Cannot Import Name in Python:

  • Circular Import
  • Incorrect Module Reference
  • Typo in Import Statement

Circular Import

To resolve circular imports, reorganize your code to eliminate the circular dependency. You can move the shared functionality to a separate module or refactor the code to break the circular link. as below code , This ensures that the import occurs when the functions are called, preventing the circular dependency at the module level.

module_a.py

Python3
# module_a.py def function_a():     from module_b import function_b     print(&quot;Function A&quot;)     function_b() 

module_b.py

Python3
# module_b.py def function_b():     from module_a import function_a     print(&quot;Function B&quot;)     function_a()  function_b() 

Output:

Function B
Function B
Function A
Function A

Correct Module Reference

Ensure that your import statements correctly reference the intended module and its names. In the second example, correcting the import statement in main.py to from mymodule import another_function will resolve the issue.

main.py

Python3
# main.py from mymodule import another_function  # Corrected import statement  another_function() 

mymodule.py

Python3
# mymodule.py def another_function():     print(&quot;Another Function&quot;) 

Output:

Another Function

Typo in Import Statement

Check for typos or spelling errors in your import statements. In the third example, correcting the import statement in myscript.py to from utils import my_function will fix the ImportError.

utils.py

Python3
# utils.py def my_function():     print(&quot;My Function&quot;) 

myscript.py

Python3
# myscript.py from utils import my_function  my_function() 

Output:

My Function

Conclusion

Handling the ImportError: Cannot Import Name in Python involves careful examination of your code for circular dependencies, correct module references, and import statement typos. By understanding the nature of the error and applying appropriate solutions, you can ensure a smoother development experience and more robust Python applications.


Next Article
Solving "ImportError in Importing from Sklearn: Cannot Import Name Check_Build"
author
sourabhsahu33
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks Premier League 2023
  • Python Errors
Practice Tags :
  • python

Similar Reads

  • Create and Import modules in Python
    In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and pac
    3 min read
  • Import Modules From Another Folder in Python
    In this article, we are going to see how to import a module from another folder, While working on big projects we may confront a situation where we want to import a module from a different directory, here we will see the different ways to import a module form different folder. It can be done in two
    2 min read
  • How to fix "ImportError: cannot import name 'joblib' from 'sklearn.externals' "
    When working with Python's famous machine learning tool scikit-learn, facing import problems can be a stressful roadblock. One common issue arises when trying to import joblib from sklearn.externals with the error message: ImportError: cannot import name 'joblib' from 'sklearn.externals'. In this ar
    2 min read
  • How To Fix Modulenotfounderror And Importerror in Python
    Two such errors that developers often come across are ModuleNotFoundError and ImportError. In this guide, we'll explore what these errors are, the common problems associated with them, and provide practical approaches to resolve them. What are ModuleNotFoundError and ImportError?ModuleNotFoundError:
    3 min read
  • Solving "ImportError in Importing from Sklearn: Cannot Import Name Check_Build"
    The ImportError: Cannot import name 'check_build' from 'sklearn.utils' usually occurs when there is an attempt to import a function that either no longer exists or has been moved in recent versions of scikit-learn. To resolve this issue, make sure that you're using a compatible version of scikit-lea
    3 min read
  • Importlib package in Python
    In this article, we are going to know about the Importlib package in the Python programming language. The importlib package is primarily utilized by Python applications for dynamic imports during runtime. In layman's terms, it allows the user to load modules as he/she discovers them. This package ha
    6 min read
  • How to Fix Django "ImportError: Cannot Import Name 'six' from 'django.utils'"?
    After Django 3.0, django.utils.six was removed. The "ImportError: Cannot Import Name 'six' from 'django.utils'" error occurs because of the dependency issue. This happens because when the project tries to use something that’s no longer available. Don’t worry—it’s easy to fix. We’ll explain why this
    3 min read
  • Import module in Python
    In Python, modules allow us to organize code into reusable files, making it easy to import and use functions, classes, and variables from other scripts. Importing a module in Python is similar to using #include in C/C++, providing access to pre-written code and built-in libraries. Python’s import st
    3 min read
  • Python - Import module outside directory
    Modules are simply a python .py file from which we can use functions, classes, variables in another file. To use these things in another file we need to first import that module into that file. If the module exists in the same directory as the file, we can directly import it using the syntax import
    4 min read
  • Lazy import in Python
    In this article, we will learn how to do Lazy import in Python. For this, let's first understand the lazy import. What is Lazy Import? It is a feature of the Pyforest module that allows the user to perform the task without adding libraries to the code snippet as the task of this function is to add t
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences