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 inside the root directory. This will signal to the python intrepter that this directory is a package.

The project directory - solution 1
 └── root
     └── package

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 with -m option
 Y:/new_root>python -m root.package.program
 __file__=Y:/new_root/root/package/ | __name__=__main__                  | __package__=root.package
 __file__=Y:/new_root/root/            |                 | __package__=root
 data.size => 10

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