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
Causes of the error
- Relative import in a script
- Incorrect package structure
- Wrong working directory
- Misuse of relative imports
- 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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.