dyn_modules¶
Dynamic module loader for discovering and importing modules from directories.
This module provides the DynLoader class which can discover Python modules in a directory or package, optionally matching a filename pattern, and import them dynamically for use as plugin-like extensions.
Example
import os
import sys
import tempfile
import py_misc_utils.dyn_modules as dym
tdir = tempfile.TemporaryDirectory()
with open(os.path.join(tdir.name, 'plug_a.py'), 'w') as fpt:
fpt.write('V = 10')
loader = dym.DynLoader(path=tdir.name)
assert loader.get('plug_a').V == 10
assert loader.module_names() == ('plug_a',)
tdir.cleanup()
sys.modules.pop('plug_a', None)
DynLoader
¶
Dynamically loads Python modules from a directory or package path.
Discovers .py files matching an optional postfix pattern in a given directory, imports them, and stores them in an ordered dictionary keyed by module name. Modules can optionally expose a MODULE_NAME attribute to override the derived name.
Source code in py_misc_utils/dyn_modules.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
module_names()
¶
Return the names of all loaded modules as a tuple.
Returns:
| Type | Description |
|---|---|
|
A tuple of strings, each being the name of a loaded module. |
Source code in py_misc_utils/dyn_modules.py
87 88 89 90 91 92 93 | |
modules()
¶
Return all loaded module objects as a tuple.
Returns:
| Type | Description |
|---|---|
|
A tuple of module objects in the order they were loaded. |
Source code in py_misc_utils/dyn_modules.py
95 96 97 98 99 100 101 | |
get(name)
¶
Retrieve a loaded module by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
The name of the module to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
|
The loaded module object, or None if no module with that name exists. |
Source code in py_misc_utils/dyn_modules.py
103 104 105 106 107 108 109 110 111 112 | |