Imports using Relative Path from Python Project Root

Viewed 168

If we have a Python project whose directory structure is as shown (also available on Github)

foo
    /data
        test.dat
    /src
        /foo
            /lib
                __init__.py
                world.py
            __init__.py
            hello.py

How can we set things up such that modules can be imported from any file via foo.<something>, where foo is the directory inside src, and <something> is the relative path from foo?

The reading of the file test.dat should work too in such a directory structure.

foo/__init__.py

import pathlib

DATA_DIR = pathlib.Path(__file__).parent.parent.parent.absolute() / 'data'

foo/hello.py

from foo.lib.world import world

def hello():
    print("Hello", world())

if __name__ == '__main__':
    hello()

foo/lib/world.py

from foo import DATA_DIR

def world():
    with open(f'{DATA_DIR}/test.dat') as f:
        name = f.readline()
        return "world, " + name
0 Answers
Related