This article will discuss the error – ImportError: Attempted Relative Import With No Known Parent Package. The primary reason for this error is that the specified module does not exist within the Python library.
In Python, the failure to import a module, module member, or other python files results in ImportError.
What Causes This Error?
Let’s take the following file structure as an example to better understand the reasons for this error.
->ProjectDirectory
|
|
|
---->myPackage1
- __init__.py
- runCode.py
|
|
|
---->myPackage2
- __init__.py
- function.py
ProjectDirectory
Consists of 2 folders : myPackage1
(runCode.py) and myPackage2
(function.py).
runCode.py
from .myPackage2 import runFunction
print("Running Code")
function.runFunction()
function.py
def runFunction():
print("Running Function")
Note that the runCode.py
program makes use of the function from function.py
by importing.
Now, let’s discuss what’s relative importing.
In runCode.py, note that a dot(.) is used in the import statement. This usage of the dot indicates a relative import. As we call a function from a different package(directory), the caller program (runCode.py) has to call one level above. Multiple directory levels require multiple dots. This is the concept of relative importing. Its counter-technique. Absolute importing requires the complete path.
Let’s look at the actual error produced by runCode.py
C:\Users\SampleFolder\PythonPrograms\ProjectDirectory\myPackage > python runCode.py Traceback (most recent call last): File "C:\Users\SampleFolder\PythonPrograms\ProjectDirectory\myPackage\runCode.py", line 1m in <module> from myPackage2 import runFunction ImportError: attempted relative import with no parent package
This is due to the fact that a parent package doesn’t exist.
How To Solve This Error?
The most straightforward approach is to make the particular package global using a setup.py file. Let’s look at the following steps to achieve the same.
Creating a Setup File
Create a Setup file using the setuptools
module from Python. The setup file defines the package to be made global.
from setuptools import setup, find_packages
setup(name = "myPackage2", packages = find_packages())
The above lines import the module from myPackage2.
Running the Setup File
Access your project directory and run the following command in your command terminal.
python setup.py install
Changing the Caller Program (runCode.py)
Remove the dot from the import statement now that the package is global.
from myPackage2 import function
print("Running Code")
function.runFunction()
Output
C:\Users\SampleFolder\PythonPrograms\ProjectDirectory\myPackage > python runCode.py Running Code Running Function
ImportError: Attempted Relative Import With No Known Parent Package Unit Tests
Let’s look at the following program that deals with unit testing.
import unittest
from ..programUtil import util
class TestUrlUtilities(unittest.SampleTestCase):
def test_simple(self):
result = name_from_link("https://pythonpool.com")
self.assertEqual(result, "Python")
if __name__ == "__main__":
unittest.main()
Output
ERROR: program_utilities(unittest.loader._FailedTest) ImportError: Failed to import test module: program_utilities Traceback (most recent call last): File "C:\Python37\lib\unittest\loader.py", line 13, in loadTestsFromName module = __import__(module_name) ImportError: attempted relative import with no known parent package
What do we do in this situation? As the error says, the test folder doesn’t contain a parent package. This means using double dots (..) to import relatively will not work.
Go to the project source directory and run the following command:
python -m unittest
This creates a src
folder for our project path. Now that our module is in the path, there is no need for a relative import (..).
ImportError: Attempted Relative Import With No Known Parent Package Django
When you import a function into your Django project, you may receive the ImportError. This is due to the fact that you cannot import relatively from a direct run script. Relative imports work only if the package has been imported completely as a module.
For example, if a code is passed through /user/stdin
, there isn’t a reference for the file’s location.
Use relative imports when running .py programs. If a relative import is a must, convert the program file as a __main__.py file within the package directory while passing the Python -m command to run the module.
ImportError: Attempted Relative Import With No Known Parent Package IntelliJ (PyCharm IDE)
In this scenario, the program files may run without error. However, the unit test can fail and produce relative import errors when run from the program file’s directory.
To solve this problem, set the working directory as the top-level project directory. After this, any unit tests or relative imports will run properly. In summary, resetting the working directory should fix the relative import errors.
Attempted Relative Import Beyond Top Level Package Error
Let’s take the following file structure as an example
myModule/ __init__.py P/ __init__.py program.py testProgram_P/ __init__.py testCode.py
testCode.py
from ..P import program
To run tests, you may pass the following command within the myModule
directory
python -m testProgram_P.testCode
This can result in the following error:
"ValueError: attempted relative import beyond top-level package"
However, within the parent folder of myModule
, testProgram_P.testCode
will run perfectly.
Why does this error occur?
This is due to the fact that Python doesn’t keep track of the package location. Therefore, upon running python -m testProgram_P.testCode
Python doesn’t take into account that the file is located in myModule
. This means writing from ..P import program
is basically trying to fetch information that does not exist anymore.
FAQs
A relative import in Python specifies the content to be imported into the project, which is relative to its exact location.
__init__.py file may contain Python code that a python package would have. However, Python will add extra attributes to the package whenever imported.
The __import__() function is used by the Python import statement to import packages into the Python project. It takes the following parameters:name
– name of the module to be importedglobals/locals
– Determines the nature of the package.fromlist
– extra objects or submodules to be imported by the modulelevel
– specifies the type of import (absolute/relative)
Conclusion
In this article, we have looked at the exception: ImportError: Attempted Relative Import With No Known Parent Package. This error shows us how much the structure of a working directory matters in Python. We have learned that Python does not consider the current working directory to be a package itself, therefore hindering relative imports.