In this article, you will learn about how to fix the ImportError: attempted relative import with no known parent package in python.
ImportError: attempted relative import with no known parent package in python is a common error and you may encounter this error while working with the python module system that is located in the python packages. A module in python is referred to as a block of code or functionality and a package in python is referred to as a directory that consists of one or more modules of python files. In this article, we are going to see how this error occurred and the solution to it. Before doing so let’s quickly see our file structure in the below section:
└── python ├── package_one ├── __init__.py │ └── one.py └── package_two ├── __init__.py └── two.py
Here, you can see that we have two package folders and both of them have one module file. Now we are going to import one module to another in the below section.
We want to run module two’s program into module one. For doing so we simply import module two to module one. See the below code example:
# package_one/one.py from .package_two import two print("I am Package One") two.sayMyLocation() # package_two/two.py def sayMyLocation(): print("I am from package Two")
Here, you can see that we simply declare a function in the two.py file and then call it into the one.py file by importing it. Let’s run our program and see what happens in the below section:
Here, you can see that instead of getting the actual output we are encountering an error. In the next section, we are going to fix this error.
The solution to this problem is very easy. All we need to do is to make our package_two global so that it can be assessable. To perform this action, at first, we need to create a file named, and inside that file, we need to set the package name that we want to import. See the below code example:
from setuptools import setup, find_packages setup( name = 'package_two', packages = find_packages() )
Here, you can see that we have provided our package name. Now we need to remove the relative path from our one.py file. To do so follow the below code example:
from package_two import two print("I am Package One") two.sayMyLocation() # Output: # I am Package One # I am from package Two
This time you can see that the error has been gone and we are getting the desired output. If you have encountered the ImportError: attempted relative import with no known parent package in your python then you may fix it by following this article.