How to Fix: ImportError: attempted relative import with no known parent package
ImportError: attempted relative import with no known parent package error occurs when attempting to import a module or package using a relative import syntax, but Python is unable to identify the parent package. In this article, we will see how to solve Importerror: Attempted Relative Import With No Known Parent Package (Python).
What is ImportError: Attempted Relative Import With No Known Parent Package?
The “ImportError: attempted relative import with no known parent package” error typically arises in Python projects with multiple modules or packages. Python uses the concept of packages and modules to organize code into manageable units. When attempting to perform a relative import, Python relies on the presence of a parent package to resolve the import statement. However, if Python cannot identify the parent package, it raises the “ImportError.”
Error Syntax:
ImportError: attempted relative import with no known parent package
Below are some of the reasons why ImportError: attempted relative import with no known parent package occurs in Python:
- Incorrect package structure
- Missing init.py file
Incorrect Package Structure
One common reason for this error is an incorrect or inconsistent package structure. Python expects a specific structure to recognize packages and modules correctly. If the package structure deviates from this standard, Python may fail to identify the parent package.
my_package/module.py
def hello():
print("Hello from module.py")
my_package/main.py
from .module import hello
def main():
hello()
if __name__ == "__main__":
main()
Output
Missing utils.py file
The utils.py file is missing in one of the directories, which is crucial for Python to recognize it as a package. Without the utils.py file, Python won’t recognize the parent package, leading to the ImportError.
folder/main.py
from .utils import some_function
def main():
some_function()
Output
Solution: ImportError: Attempted Relative Import With No Known Parent Package
Below are the solution for mportError: Attempted Relative Import With No Known Parent Package in Python:
- Correct Package Structure
- Create utils.py File
Correct Package Structure
Correct the code of main.py file as shown below then run the code.
my_package/main.py
from module import hello
def main():
hello()
if __name__ == "__main__":
main()
Output
Hello from module.py
Create utils.py ( Missing) File
Create utils.py file and write below code and also correct the code of main.py file, the error will resolve.
folder/utils.py
#utils.py
def some_function():
print("This is some_function() from utils.py")
folder/main.py
from utils import some_function
def main():
some_function()
if __name__ == "__main__":
main()
Output
This is some_function() from utils.py