ImportError: attempted relative import with no known parent package

You are trying to use relative imports in python but you encounter one of the following exceptions :

  • ImportError: attempted relative import with no known parent package
  • ValueError: attempted relative import beyond top-level package
  • SystemError: Parent module '' not loaded, cannot perform relative import

Why the python interpreter complains ?
What did you do wrong ?

Why python can't resolve relative import ?

Let's see an example how we get those exception. Suppose you have the following directory structure:

Project Directory
 project
 ├── config.py
 └── package
     ├── __init__.py
     └── demo.py
The config.py contains some variables which should be used in the demo.py
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 try to run demo, we encounter the following error:

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

You may also encounter the following errors if you use newer version of python:

Error in python 2.7
 $ python demos/demo.py
 Traceback (most recent call last):
   File "project/package/demo.py", line 1, in <module>
     from .. import config
 ValueError: attempted relative import beyond top-level package
Error in python 3
 $ python demos/demo.py
 Traceback (most recent call last):
   File "demos/demo.py", line 1, in <module>
     from .. import config
 SystemError: Parent module '' not loaded, cannot perform relative import

The python interpreter complains that there is no parent package or that Parent module '' not loaded. Why?

In the next parts we see how python interpreter resolve relative modules and provide solutions to this problem.