pip install mximport
Relative imports in Python is annoying because they prevent the current code from being run directly.
For example:
A python file in pkg/main.py
from .utils import *
if __name__ == "__main__":
print("This is the main file")
Run bash:
~/pkg$ tree .
pkg/
โโโ __init__.py
โโโ main.py
โโโ utils.py
~/pkg$ python main.py # Running it directly will result in an ImportError
Traceback (most recent call last):
File "~/pkg/main.py", line 1, in <module>
from .utils import *
ImportError: attempted relative import with no known parent package
mximport.inpkg()
can remove this limitation:
# new pkg/main2.py
from mximport import inpkg
with inpkg():
from .utils import *
if __name__ == "__main__":
print("This is the main2 file")
~/pkg$ python main2.py # Every thing is OK!
This is the main2 file
Say goodbye to python -m pkg.main
Temporary add the relative path to sys.path during with statement
Usage๏ผ
from mximport import syspath
with syspath(".."): # relative path
import father_module
with syspath("/abspath/to/module's/dir"):
import module
Directly import .py
file or package by path, return a moudle object
from mximport import import_by_path
module = import_by_path('/path/to/module.py')
pkg = import_by_path('/path/to/pkg')
relative_module = import_by_path('../relative_module.py')
- Simple source code and zero dependency
- Widely applicable: Testing and polishing since 2018 within boxx