ImportError: attempted relative import with no known parent package

You are trying to use relative imports in python, but you encounter the exception ImportError: attempted relative import with no known parent package. Yes, relative imports can be confusing from time to time. In this article, we see the method used by python interpreter to resolve the relative imports and how we can fix this issue.

Example for ImportError: attempted relative import with no known parent package

Let's see an example of how we get those exceptions. Suppose your project have the following directory structure:

Project Directory
 project
 ├── config.py
 └── package
     ├── __init__.py
     └── demo.py

The config.py contains some variables which want to access in demo.py. You decide to use relative import to achieve this simple task.

project/config.py
 count = 5
project/package/demo.py
 from .. import config
 print("The value of config.count is {0}".format(config.count))

When we invoke the demo script, we encounter the following error:

Exception
 Y:/project>python package/demo.py
 Traceback (most recent call last):
   File "package/demo.py", line 1, in <module>
     from .. import config
 ImportError: attempted relative import with no known parent package

In the next parts, we see how python interpreter resolve relative imports and how to fix this annoying issue.