Importerror attempted relative import with no known parent package error occurs when we import any module from any package (Directory) where __init__.py file is missing or the path for the package is undefined. In this article, We will practically fix this problem.
Importerror attempted relative import with no known parent package ( Cause ) –
In order to understand the cause let’s take a scenario for example. Suppose this is the file structure –
As you can see, we are having two packages –
package_one -> script.py
Here is the code inside script.py-
from .package_two import functionality print("Running Script file") functionality.execute()
package_two -> functionality.py
## functionality.py file def execute(): print("Running functionality")
Now you can see that we are importing package_two module functionality.py in the script.py file of package_one.
Relative Import –
While importing we use (.) dot before as you can see below image. This makes it a relative import. Let me explain since we are calling functionality modules from script.py files which are belonging to different packages( directories). Hence the caller file (script.py ) has to go one level up that is why one (.) dot. If suppose there are more directory levels we can use multiple dots for the same.
This is called relative importing while absolute importing needs a full path for the same.
Let’s run and see the error-
since we do not have a parent package define.
Importerror attempted relative import with no known parent package ( Solution) –
The easiest way to fix this relative import error is using the setup.py file, we can make the respective package global. Here are the steps-
Step 1: Create setup.py file-
All you need to create a simple python file with a setup name. Here we will define which package we want to make global.
from setuptools import setup, find_packages setup(name = 'package_two', packages = find_packages())
In the above example, We are importing module from package_two.
Step 2: Running setup.py file –
Use the below command –
python setup.py install
Step 3: Modifying caller script –
We need to call this script.py file but as we have made this package global so need to remove this (.) in importing statement.
from package_two import functionality print("Running Script file") functionality.execute()
Now, let’s run this script.py file.
Hey !! we have cracked the same.
As an alternative to this approach, we can also move the relevant package to the directory where we have a path set.
Or we can copy the same package to any existing directory for which path is already configured.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.