From 4a15b5b81c2423a11632dc8c136e1bbf7077bdfc Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sat, 16 Jan 2010 00:34:19 -0800 Subject: [PATCH] Fixed issue where patcher wasn't correctly restoring modules after an importerror. --- eventlet/hubs/__init__.py | 2 +- eventlet/patcher.py | 42 ++++++++++++++++++++------------------- 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/eventlet/hubs/__init__.py b/eventlet/hubs/__init__.py index 3ad3c72..2121cfc 100644 --- a/eventlet/hubs/__init__.py +++ b/eventlet/hubs/__init__.py @@ -73,4 +73,4 @@ def get_hub(): except AttributeError: use_hub() hub = _threadlocal.hub = _threadlocal.Hub() - return hub \ No newline at end of file + return hub diff --git a/eventlet/patcher.py b/eventlet/patcher.py index 66f9d4c..68e21bb 100644 --- a/eventlet/patcher.py +++ b/eventlet/patcher.py @@ -13,28 +13,30 @@ def inject(module_name, new_globals, *additional_modules): ## Remove the old module from sys.modules and reimport it while the specified modules are in place old_module = sys.modules.pop(module_name, None) - module = __import__(module_name, {}, {}, module_name.split('.')[:-1]) + try: + module = __import__(module_name, {}, {}, module_name.split('.')[:-1]) - if new_globals is not None: - ## Update the given globals dictionary with everything from this new module - for name in dir(module): - if name not in __exclude: - new_globals[name] = getattr(module, name) + if new_globals is not None: + ## Update the given globals dictionary with everything from this new module + for name in dir(module): + if name not in __exclude: + new_globals[name] = getattr(module, name) - ## Keep a reference to the new module to prevent it from dying - sys.modules['__patched_module_' + module_name] = module - ## Put the original module back - if old_module is not None: - sys.modules[module_name] = old_module - else: - del sys.modules[module_name] + ## Keep a reference to the new module to prevent it from dying + sys.modules['__patched_module_' + module_name] = module + finally: + ## Put the original module back + if old_module is not None: + sys.modules[module_name] = old_module + elif module_name in sys.modules: + del sys.modules[module_name] - ## Put all the saved modules back - for name, mod in additional_modules: - if saved[name] is not None: - sys.modules[name] = saved[name] - else: - del sys.modules[name] + ## Put all the saved modules back + for name, mod in additional_modules: + if saved[name] is not None: + sys.modules[name] = saved[name] + else: + del sys.modules[name] return module @@ -63,4 +65,4 @@ def patch_function(func, *additional_modules): else: del sys.modules[name] return patched - \ No newline at end of file +