How to Fix ImportError: attempted relative import with no known parent package

ImportError: attempted relative import with no known parent package error occurs when you try to “use a relative import in a Python script executed as the main script” (i.e., not being imported as a module into another script).

To fix the error, use the “absolute imports”, “refactor your code”, or “-m flag to run the script as a module”.

Flowchart

Flowchart of Fixing ImportError: attempted relative import with no known parent package

Causes of the error

  1. Relative import in a script
  2. Incorrect package structure
  3. Wrong working directory
  4. Misuse of relative imports
  5. Running modules as scripts

How to fix it?

Solution 1: Use the absolute imports

You can change the relative imports to absolute imports by specifying the complete module path, starting from the top-level package. This makes your imports independent of the script’s location within the package.

# Instead of using a relative import like this
from .my_module import my_function

# Use an absolute import
from my_package.my_module import my_function

Solution 2: Refactor your code

Rearrange your code to ensure that relative imports are only used within a package, and create a separate top-level script that imports and runs the desired functionality from the package.

my_package/
  __init__.py
  my_module.py
  another_module.py
main_script.py

In this example, both my_module.py and another_module.py can use relative imports to access other modules within the my_package package.

The main_script.py should use absolute imports to access modules within my_package.

Solution 3: Use the -m flag to run the script as a module

To use relative imports in the main script, you can run the script as a module using the -m flag. However, your script must be inside a package with an __init__.py file.

python -m my_package.my_script

This command runs the my_script.py file inside the my_package package as a module, allowing you to use relative imports within the script.

Choose the option that best fits your project structure and requirements to resolve the ImportError: attempted relative import with no known parent package error.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.