Duplicating Modules

Dave Benjamin ramen at lackingtalent.com
Fri Sep 30 16:22:51 EDT 2005


Misto . wrote:
> Hi folks!
> 
> Short:
> 
> There is a way to dumplicate a module ?

Here's one way... it doesn't quite work with modules inside of packages, 
unfortunately, but it does avoid defeating module caching and tries to 
keep sys.modules in a predictable state. I don't know what the 
thread-safety implications are for this sort of trickery with sys.modules.

def import_as(newname, oldname):
     """Import a module under a different name.

     This procedure always returns a brand new module, even if
     the original module has always been imported.

     Example::

         try:
             # Reuse this module if it's already been imported
             # as "mymath".
             import mymath
         except ImportError:
             # "mymath" has not yet been imported.
             # Import and customize it.
             mymath = import_as('mymath', 'math')
             mymath.phi = (mymath.sqrt(5.0) - 1.0) / 2.0

     The above code will not reinitialize "mymath" if it executes
     a second time (ie. if the module containing this code is
     reloaded). Whether or not "math" has already been imported,
     it will always be a different object than "mymath".
     """

     import sys
     if sys.modules.has_key(oldname):
         tmp = sys.modules[oldname]
         del sys.modules[oldname]
         result = __import__(oldname)
         sys.modules[newname] = sys.modules[oldname]
         sys.modules[oldname] = tmp
     else:
         result = __import__(oldname)
         sys.modules[newname] = sys.modules[oldname]
         del sys.modules[oldname]
     return result

Dave



More information about the Python-list mailing list