Skip to content

magic-python-toolbox/mximport

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

6 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

mximport: Remove all limits on Python package imports ๐Ÿš€

pip install mximport

โ–ฎ Painless Relative Import

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 relative path in sys.path

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

โ–ฎ Import by Path

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')

โ–ฎ Other Features

  • Simple source code and zero dependency
  • Widely applicable: Testing and polishing since 2018 within boxx