No known parent package - Solution 1

Let's change directory structure and cretae a new script

  • First, create a new directory named new_project
  • Move the project directory to new_project
  • Create a new empty __init__.py inside the root directory - this will make the directory to a package.
  • Create main.py in new_project directory

The project directory - solution 1
 new_project
 ├── main.py
 └── project
     ├── __init__.py
     ├── config.py
     └── package
         ├── __init__.py
         └── demo.py
Updating new_project/main.py
 print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__)))

 import project.package.demo

When we run the demo, we get the following output:

Invoking Solution 1
 Y:/new_project>python main.py
 __file__=main.py                                | __name__=__main__                  | __package__=None
 __file__=Y:/new_project/project/package/demo.py | __name__=project.package.demo      | __package__=project.package
 __file__=Y:/new_project/project/config.py       | __name__=project.config            | __package__=project
 The value of config.count is 5

As we can see, importing project.package.demo in main.py will set the package information (__name__ and __package__ variables). Now, the python interpreter can resolve the relative import in project/demos/demo.py successfully.

In the next part, we will see another solution which use the -m option of python