Duplicating Modules

M

Misto .

Hi folks!

Short:

There is a way to dumplicate a module ?

I tried
copy.deepcopy(module) but hangs with an error (also with standard modules )..

The only solution that I have by now is creating two files and importing them.
I.E:
cp module.py module1.py


Any Ideas?

P.S: I know that there is some design Issue here, but my boss says no :)

Misto
 
D

Dave Benjamin

Misto said:
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
 
S

Steven D'Aprano

There is a way to dumplicate a module ?
[snip]

P.S: I know that there is some design Issue here, but my boss says no :)

It depends on what you are expecting to do with the duplicated module. If
all you need is to access the same module from two different names, you
can do this:

py> import sys
py> my_boss_is_an_idiot = sys # *grins*
py> my_boss_is_an_idiot.version
'2.3.3 (#1, May 7 2004, 10:31:40) \n[GCC 3.3.3 20040412 (Red Hat Linux
3.3.3-7)]'


But keep in mind that using this method, sys and my_boss_is_an_idiot are
merely different names for the same underlying module. Change one and you
change the other.

I'm curious... I don't expect you to comment on your boss' mental state,
but how/why do you need to duplicate the module?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top