hbutils.reflection.module¶
mount_pythonpath¶
-
hbutils.reflection.module.
mount_pythonpath
(*path) → AbstractContextManager[hbutils.reflection.module.PythonPathEnv][source]¶ - Overview:
Append
PYTHONPATH
in context, the packages in given paths will be able to be imported.sys.modules
will also be recovered when quit.
- Parameters:
path – Appended python path.
- Examples::
Here is the testfile directory
>>> import os >>> os.system('tree test/testfile') test/testfile ├── dir1 │ ├── gf1.py ├── dir2 │ ├── gf1.py └── igm └── gf1.py
We can import the values from the other directories, like this
>>> from hbutils.reflection import mount_pythonpath >>> with mount_pythonpath('test/testfile/igm'): ... from gf1 import FIXED ... print('FIXED in igm:', FIXED) FIXED in igm: 1234567 >>> >>> with mount_pythonpath('test/testfile/dir1'): ... from gf1 import FIXED ... print('FIXED in dir1:', FIXED) FIXED in dir1: 233 >>> >>> with mount_pythonpath('test/testfile/dir2'): ... from gf1 import FIXED ... print('FIXED in dir2:', FIXED) FIXED in dir2: 455 >>> >>> from gf1 import FIXED # cannot import outside ModuleNotFoundError: No module named 'gf1'
PythonPathEnv¶
-
class
hbutils.reflection.module.
PythonPathEnv
(pythonpath: List[str], modules: Mapping[str, module])[source]¶ - Overview:
Python environment object.
-
__init__
(pythonpath: List[str], modules: Mapping[str, module])[source]¶ Constructor of
PythonPathEnv
.- Parameters:
pythonpath – Python path list.
modules – Modules loaded.
-
mount
(keep: bool = True) → AbstractContextManager[hbutils.reflection.module.PythonPathEnv][source]¶ Mount the
PYTHONPATH
and modules of this environment.- Parameters:
keep – Keep the changes inside. Default is
True
which means the new imports and modules will be kept inside and will be usable when next time themount()
is called.
- Examples::
>>> from hbutils.reflection import mount_pythonpath >>> with mount_pythonpath('test/testfile/igm') as env: ... from gf1 import FIXED ... print('FIXED in igm:', FIXED) FIXED in igm: 1234567 >>> with env.mount(): ... from gf1 import FIXED ... print('FIXED in igm:', FIXED) FIXED in igm: 1234567