No known parent package - How relative imports works in python

Let's see how python interpreter resolve relative module. From PEP 328 -- Imports: Multi-Line and Absolute/Relative which introduce the relative imports we found that:

Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy.

In other words, the algorithm to resolve the module is based on the values of __name__ and __package__ variables.

Sometimes , as in our example case, those variables does not contain any package information - the value of __package__ is None and the value of __name__ is __main__. let's see how relative imports are resolved in this case:

If the module's name does not contain any package information (e.g., it is set to __main__), then relative imports are resolved as if the module were a top-level module, regardless of where the module is actually located on the file system.

Let's add some logging to our example to demonstrate this particular case

project/config.py with logs
 print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__)))

 count = 5
project/package/demo.py with logs
 print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__)))

 from .. import config
 print("The value of config.count is {0}".format(config.count))

When we try to run the script demo.py, we encounter the following output:

Error with logs
 Y:/project>python package/demo.py
 __file__=package/demo.py                     | __name__=__main__                  | __package__=None
 Traceback (most recent call last):
   File "package/demo.py", line 3, in <module>
     from .. import config
 ImportError: attempted relative import with no known parent package

As we can see, __name__ is __main__ and __package__ is None. In other words, the python interpreter does not have any information about the package the module belong. Therefore it complains that it can not find the parent package. Let's see how can we resolve this issue