I was reading today about absolute and relative imports in Python, and I was wondering if there is a pythonic way of making an import work when the script that contains the import is used as a module and when it is called directly. As an example:
└── project
├── main.py
└── package
├── submoduleA.py
└── submoduleB.py
main.py
from package.submoduleA import submoduleAfunction
submoduleAfunction()
submoduleB.py
def submoduleBfunction():
print('Hi from submoduleBfunction')
submoduleA.py
# Absolute import, works when called directly: python3 package/submoduleA.py
from submoduleB import submoduleBfunction
# Relative import, works when imported as module: python3 main.py
# from .submoduleB import submoduleBfunction
def submoduleAfunction():
submoduleBfunction()
if __name__=="__main__":
submoduleAfunction()
As you see, I have there both absolute and relative imports. Each of them works in a specific situation. But is there a pythonic way of making it work for both cases? So far I've done the trick messing with sys.path
, but I'm not sure that this will work in every situation (i.e. called from interpreter or in different OS's) or even if this goes against any recommendations.
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.resolve()))