ValueError: attempted relative import beyond top-level package

Relative import in python can be sometimes mysterious and obscure. From time to time, you may encounter the exception ValueError: Attempted relative import beyond top-level package. Let's see how can you fix this error.

Sample for ValueError: attempted relative import beyond top-level package

Suppose you have a project with the following simple directory structure:

Project directory structure
 root
 ├── data.py
 └── package
     ├── __init__.py
     └── program.py

You are trying access variables defined in the data.py in your program.py. It seems a straightforward task and you choose to use relative import:

root/data.py
 size = 10
root/package/program.py
 from .. import data
 print("data.size => {0}".format(data.size))

However, when invoking program.py script, An exception is raised :

Invoking program.py and the raised exception
 Y:/root>python package/program.py
 Traceback (most recent call last):
   File "package/program.py", line 1, in <module>
     from .. import data
 ValueError: attempted relative import beyond top-level package

In the next parts, we see how relative modules are resolved by python interpreter and how to fix this problem.