Skip to main content

How to Resolve Python Error "ImportError: cannot import name 'X'"

The ImportError: cannot import name 'X' from 'module_name' is a common Python error that signals a problem during the import process. It means Python was able to find the specified module (module_name), but it could not find the specific name (X - which could be a function, class, variable, or submodule) within that module that you were trying to import directly.

This guide explores the various reasons for this error, including circular imports, spelling mistakes, version incompatibilities, and module shadowing, providing clear solutions for each.

Understanding the Error: Python's Import Mechanism

When you write from module_name import X, Python performs several steps:

  1. Finds module_name: It searches for module_name.py (or a package directory named module_name) in standard locations (sys.path). If this fails, you get a ModuleNotFoundError.
  2. Loads module_name: If found, Python executes the module's code to make its contents available.
  3. Looks for X in module_name: It then tries to find the specific name X (function, class, variable) within the loaded module_name.

The ImportError: cannot import name 'X' occurs at step 3: the module was found and loaded, but the specific name X isn't defined or accessible directly from that module's top level in the way you're trying to import it.

Common Causes and Solutions

Circular Imports

  • Cause: Two or more modules try to import each other, creating a dependency loop. For example, a.py imports something from b.py, and b.py (at the same time, during its own import process) tries to import something from a.py. Python might partially initialize one module, and when the other tries to import a name from it, that name might not be defined yet.

  • Example:

    a_module.py
    from b_module import func_b # Imports from b_module

    def func_a():
    print("Function A calling func_b:")
    return func_b(5)

    if __name__ == "__main__":
    print(f"func_a result: {func_a()}") # Triggers b_module import
    b_module.py
    from a_module import func_a # ⛔️ Imports from a_module (circular)

    def func_b(x):
    print("Function B called")
    return x * 2

    # This line might cause the error if a_module isn't fully initialized when b_module tries to import func_a
    print(f"func_a() from b_module: ERROR WILL OCCUR HERE OR IN a_module")
    # print(func_a()) # Example call that would also fail

    Running python a_module.py would likely lead to an ImportError (e.g., cannot import name 'func_b' from partially initialized module 'b_module' (most likely due to a circular import) or similar for func_a).

  • Solution: Refactor to Avoid Circularity

    • Move Shared Code: Identify functions or classes used by both modules and move them to a new, third module (e.g., utils.py). Both original modules can then import from this utility module without importing each other.
      utils.py
      def shared_func_for_a(): return "Data for A"
      def shared_func_for_b(): return "Data for B"
      a_module_fixed.py
      from utils import shared_func_for_a
      # from b_module_fixed import some_other_func_from_b # if needed, but not func_b if it uses a_module
      print(shared_func_for_a())
      b_module_fixed.py
      from utils import shared_func_for_b
      print(shared_func_for_b())
    • Import Within Functions (Lazy Import): Only import the needed module inside the function where it's used. This breaks the import cycle at the module's load time but can have slight performance implications if the function is called frequently. Use sparingly.
    • Re-architect Dependencies: Rethink the design so that one module clearly depends on the other, but not vice-versa at the top level.

Misspelled Name (Function, Class, or Module)

  • Cause: A simple typo in the name of the object you're trying to import or the module you're importing from. Names are case-sensitive.
  • Example:
    error_misspelled.py
    try:
    # ⛔️ Misspelled 'Array' (should be 'array' for numpy.array)
    from numpy import Array
    print(Array)
    except ImportError as e:
    print(e) # Output: cannot import name 'Array' from 'numpy'
  • Solution: Verify Spelling and Case Carefully check the spelling and capitalization against the module's documentation or source code.
    solution_correct_spelling.py
    from numpy import array # ✅ Corrected 'array' (lowercase)
    print(array)

Name Not Available in Module/Version

  • Cause: The function, class, or variable (X) you are trying to import:
    • Simply doesn't exist in the top-level namespace of module_name. It might be in a submodule (e.g., module_name.submodule.X).
    • Was added in a newer version of module_name than what you have installed.
    • Was removed or relocated in a newer version of module_name (common with library API changes).
    • If importing from the standard library (e.g., typing, collections), the feature might only be available in a newer Python version.
  • Solution: Check Documentation, Update Module/Python, or Use Alternatives
    1. Consult Documentation: Check the official documentation for module_name to verify the correct import path and availability of X in your installed version.
    2. Update Module: If X was added in a newer version, update the module:
      pip install --upgrade module_name
    3. Check Python Version: If X is a standard library feature, verify your Python version (python --version) supports it. You might need to upgrade Python or use typing_extensions for backports.
    4. Use Correct Import Path: If X is in a submodule, import it correctly: from module_name.submodule import X.
    5. Find Alternatives: If X was removed, the documentation usually suggests a replacement or a new way to achieve the same functionality.

Filename Shadowing (Local File Masks Installed Module)

  • Cause: You have created a Python file in your project directory (or in a directory that's high on sys.path) with the same name as a standard library module or an installed third-party module (e.g., math.py, requests.py, sys.py). When you try from math import sqrt, Python finds your local math.py first, which likely doesn't define sqrt, leading to the ImportError.
  • Example: If you have a file named string.py in your project and try:
    # In another project file, if 'string.py' exists locally:
    try:
    # ⛔️ Imports your local string.py, not the standard library module
    from string import ascii_lowercase
    print(ascii_lowercase)
    except ImportError as e:
    print(e) # Output: cannot import name 'ascii_lowercase' from 'string'
  • Solution: Rename Your Local File Rename your local script to something unique that doesn't clash with installed module names (e.g., my_string_utils.py).

Incorrect Import Path for Submodules/Classes

  • Cause: Trying to import a class or submodule as if it were a top-level member when it's nested.
  • Example:
    # Incorrect for importing datetime class
    # from datetime import datetime.datetime # ⛔️ This is wrong syntax
  • Solution: Use Correct Dotted Path
    from datetime import datetime # ✅ Correct: imports the datetime CLASS from the datetime MODULE
    # OR
    import datetime # Imports the module
    dt_obj = datetime.datetime.now() # Access class via module.class

Debugging Techniques

Import the Entire Module and Use dir()

If from module_name import X fails, try importing just the module and then inspecting its contents:

import module_name # Replace with the actual module

print(dir(module_name))
# Now look through the printed list of names to see if 'X' is there,
# or if it's spelled differently, or if it's inside a submodule.

Use IDE Autocompletion

Modern IDEs (VS Code, PyCharm, etc.) usually provide autocompletion.

  • After from module_name import (with a space), trigger autocompletion (often Ctrl+Space). It should suggest available names.
  • After import module_name and then module_name. (with a dot), trigger autocompletion.

Check Module/Python Versions

  • Module Version: pip show module_name (check the Version: line).
  • Python Version: python --version. Compare these with the package's documentation regarding when X was introduced or deprecated.

Special Case: Jupyter Notebook (Restart Kernel)

If you recently installed or updated a module while a Jupyter Notebook kernel was running, the kernel might not immediately recognize the changes. Try restarting the kernel (Kernel menu -> Restart Kernel...) and then re-run your import cells.

Conclusion

The ImportError: cannot import name 'X' means Python found the module but not the specific name X within it. The key to solving this is to systematically check:

  1. Circular Imports: Refactor to break dependency loops, often by moving shared code to a third file.
  2. Spelling and Case: Double-check the exact name of the function, class, or variable you're importing.
  3. Availability: Confirm X exists in the installed version of the module and is compatible with your Python version. Consult documentation and update packages/Python if needed.
  4. Filename Shadowing: Ensure your local script names don't conflict with standard or third-party module names.
  5. Correct Import Path: Use the proper dotted path for nested classes or submodules.

Notice that dir() and IDE autocompletion are valuable debugging tools.