In the below hierachy, is there a convenient and universal way to reference to the top_package using a generic term in all .py file below? I would like to have a consistent way
Put your package and the main
script into an outer container directory, like this:
container/
main.py
top_package/
__init__.py
level_one_a/
__init__.py
my_lib.py
level_two/
__init__.py
hello_world.py
level_one_b/
__init__.py
my_lib.py
When main.py
is run, its parent directory (container
) will be automatically added to the start of sys.path
. And since top_package
is now in the same directory, it can be imported from anywhere within the package tree.
So hello_world.py
could import level_one_b/my_lib.py
like this:
from top_package.level_one_b import my_lib
No matter what the name of the container directory is, or where it is located, the imports will always work with this arrangement.
But note that, in your original example, top_package
it could easily function as the container directory itself. All you would have to do is remove top_package/__init__.py
, and you would be left with efectively the same arrangement.
The previous import statement would then change to:
from level_one_b import my_lib
and you would be free to rename top_package
however you wished.