From bf9fd841dac717d51d54eaafb588fb29147860d6 Mon Sep 17 00:00:00 2001 From: Fred Drake Date: Fri, 2 Jul 2004 20:54:55 +0000 Subject: [PATCH] Merge revision 26067 from the trunk: Re-write test to allow re-running in a loop. This test assumes that a module from the standard library has not been imported, which means it is very fragile and could be broken by unrelated changes elsewhere. Instead, create a temporary module specifically for the test, and clean it up when the test is done. --- classmodule/__init__.py | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/classmodule/__init__.py b/classmodule/__init__.py index b8db0a50..18d7a640 100644 --- a/classmodule/__init__.py +++ b/classmodule/__init__.py @@ -642,7 +642,7 @@ def cleanUp(): def safe_import(path, default=None): - """Import a given path as efficiently as possible and without failure. + r"""Import a given path as efficiently as possible and without failure. First we try to find the path in 'sys.modules', since this lookup is much more efficient than importing it. If it was not found, we go back and try @@ -655,13 +655,32 @@ def safe_import(path, default=None): >>> safe_import('zope.app') is sys.modules['zope.app'] True - >>> 'shelve' in sys.modules - False - >>> safe_import('shelve').__name__ - 'shelve' - >>> safe_import('weirdname') is None True + + For this example, we'll create a dummy module: + + >>> here = os.path.dirname(__file__) + >>> filename = os.path.join(here, 'testmodule.py') + >>> f = open(filename, 'w') + >>> f.write('# dummy module\n') + >>> f.close() + + The temporary module is not already imported, but will be once + we've called safe_import(): + + >>> module_name = __name__ + '.testmodule' + >>> module_name in sys.modules + False + >>> safe_import(module_name).__name__ == module_name + True + >>> module_name in sys.modules + True + >>> del sys.modules[module_name] + + Now clean up the temporary module, just to play nice: + + >>> os.unlink(filename) """ module = sys.modules.get(path, default) if module is default: