#11910: change import_fresh_module to return None when one of the "fresh" modules can not be imported.

This commit is contained in:
Ezio Melotti 2011-05-09 06:28:42 +03:00
parent 7055064bbb
commit 193c34ba86
1 changed files with 8 additions and 4 deletions

View File

@ -84,12 +84,14 @@ def import_module(name, deprecated=False):
def _save_and_remove_module(name, orig_modules): def _save_and_remove_module(name, orig_modules):
"""Helper function to save and remove a module from sys.modules """Helper function to save and remove a module from sys.modules
Return value is True if the module was in sys.modules and Return True if the module was in sys.modules, False otherwise.
False otherwise.""" Raise ImportError if the module can't be imported."""
saved = True saved = True
try: try:
orig_modules[name] = sys.modules[name] orig_modules[name] = sys.modules[name]
except KeyError: except KeyError:
# try to import the module and raise an error if it can't be imported
__import__(name)
saved = False saved = False
else: else:
del sys.modules[name] del sys.modules[name]
@ -99,8 +101,7 @@ def _save_and_remove_module(name, orig_modules):
def _save_and_block_module(name, orig_modules): def _save_and_block_module(name, orig_modules):
"""Helper function to save and block a module in sys.modules """Helper function to save and block a module in sys.modules
Return value is True if the module was in sys.modules and Return True if the module was in sys.modules, False otherwise."""
False otherwise."""
saved = True saved = True
try: try:
orig_modules[name] = sys.modules[name] orig_modules[name] = sys.modules[name]
@ -116,6 +117,7 @@ def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
the sys.modules cache is restored to its original state. the sys.modules cache is restored to its original state.
Modules named in fresh are also imported anew if needed by the import. Modules named in fresh are also imported anew if needed by the import.
If one of these modules can't be imported, None is returned.
Importing of modules named in blocked is prevented while the fresh import Importing of modules named in blocked is prevented while the fresh import
takes place. takes place.
@ -137,6 +139,8 @@ def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
if not _save_and_block_module(blocked_name, orig_modules): if not _save_and_block_module(blocked_name, orig_modules):
names_to_remove.append(blocked_name) names_to_remove.append(blocked_name)
fresh_module = importlib.import_module(name) fresh_module = importlib.import_module(name)
except ImportError:
fresh_module = None
finally: finally:
for orig_name, module in orig_modules.items(): for orig_name, module in orig_modules.items():
sys.modules[orig_name] = module sys.modules[orig_name] = module