Import and return a module, deliberately bypassing sys.modules. This function imports and returns a fresh copy of the named Python module by removing the named module from sys.modules before doing the import. Note that unlike reload, the original module is not affected by this opera
(name, fresh=(), blocked=(), *,
deprecated=False,
usefrozen=False,
)
| 140 | |
| 141 | |
| 142 | def import_fresh_module(name, fresh=(), blocked=(), *, |
| 143 | deprecated=False, |
| 144 | usefrozen=False, |
| 145 | ): |
| 146 | """Import and return a module, deliberately bypassing sys.modules. |
| 147 | |
| 148 | This function imports and returns a fresh copy of the named Python module |
| 149 | by removing the named module from sys.modules before doing the import. |
| 150 | Note that unlike reload, the original module is not affected by |
| 151 | this operation. |
| 152 | |
| 153 | *fresh* is an iterable of additional module names that are also removed |
| 154 | from the sys.modules cache before doing the import. If one of these |
| 155 | modules can't be imported, None is returned. |
| 156 | |
| 157 | *blocked* is an iterable of module names that are replaced with None |
| 158 | in the module cache during the import to ensure that attempts to import |
| 159 | them raise ImportError. |
| 160 | |
| 161 | The named module and any modules named in the *fresh* and *blocked* |
| 162 | parameters are saved before starting the import and then reinserted into |
| 163 | sys.modules when the fresh import is complete. |
| 164 | |
| 165 | Module and package deprecation messages are suppressed during this import |
| 166 | if *deprecated* is True. |
| 167 | |
| 168 | This function will raise ImportError if the named module cannot be |
| 169 | imported. |
| 170 | |
| 171 | If "usefrozen" is False (the default) then the frozen importer is |
| 172 | disabled (except for essential modules like importlib._bootstrap). |
| 173 | """ |
| 174 | # NOTE: test_heapq, test_json and test_warnings include extra sanity checks |
| 175 | # to make sure that this utility function is working as expected |
| 176 | with _ignore_deprecated_imports(deprecated): |
| 177 | # Keep track of modules saved for later restoration as well |
| 178 | # as those which just need a blocking entry removed |
| 179 | fresh = list(fresh) |
| 180 | blocked = list(blocked) |
| 181 | names = {name, *fresh, *blocked} |
| 182 | orig_modules = _save_and_remove_modules(names) |
| 183 | for modname in blocked: |
| 184 | sys.modules[modname] = None |
| 185 | |
| 186 | try: |
| 187 | with frozen_modules(usefrozen): |
| 188 | # Return None when one of the "fresh" modules can not be imported. |
| 189 | try: |
| 190 | for modname in fresh: |
| 191 | __import__(modname) |
| 192 | except ImportError: |
| 193 | return None |
| 194 | return importlib.import_module(name) |
| 195 | finally: |
| 196 | _save_and_remove_modules(names) |
| 197 | sys.modules.update(orig_modules) |
| 198 | |
| 199 |
searching dependent graphs…