ValueError: attempted relative import beyond top-level package - part 4

Solution 2 - Change directory structure and use -m option

  • First, create a new directory named new_root
  • Move the root directory to new_root
  • Create a new empty __init__.py inside the root directory. This will signal to the python intrepter that this directory is a package.

The project directory - solution 1
 new_root  
 └── root
     ├── __init__.py
     ├── data.py
     └── package
         ├── __init__.py
         └── program.py

Now, we invoke the root.package.program with -m option. The python -m option allows modules to be located using the Python module namespace for execution as scripts. As the following output demonstrate, It will also set the package information:

Invoking program.py with -m option
 Y:/new_root>python -m root.package.program
 __file__=Y:/new_root/root/package/program.py | __name__=__main__                  | __package__=root.package
 __file__=Y:/new_root/root/data.py            | __name__=root.data                 | __package__=root
 data.size => 10

Now, when the python interpreter knows the package information, it can successfully resolve the relative import in root/package/program.py