Skip to content Skip to sidebar Skip to footer

Importing Module As It Was A Level Higher

I have this directory structure obtained with setuptools: root/ A/ __init__.py 1.py 2.py B/ __init__.py 3.py __init__.py the package sect

Solution 1:

Modifying the __path__ variable might help.


# root/__init__.py
import os
__path__.append(os.path.join(os.path.dirname(__file__), 'A'))
# root/A/__init__.py# empty
# root/A/one.py
def first_func():
    print("first_func belongs to:", __name__, "in:", __file__)

This allows to do the following:

$ python3 -c "from root import one; one.first_func()"
first_func belongs to: root.one in: /home/sinoroc/workspace/root/.venv/lib/python3.6/site-packages/root-0.0.0.dev0-py3.6.egg/root/A/one.py

As well as:

$ python3 -c "from root.A import one; one.first_func()"
first_func belongs to: root.A.one in: /home/sinoroc/workspace/root/.venv/lib/python3.6/site-packages/root-0.0.0.dev0-py3.6.egg/root/A/one.py

See:

Post a Comment for "Importing Module As It Was A Level Higher"