[Python-Help] imp.load_module from a string

Chris Withers chrisw at nipltd.com
Mon Jul 10 06:58:24 EDT 2000


Thanks for the help so far :-)

Okay, another question: What is the difference between the contents of a
.pyc file and what is returned by compile(str,'notafile','exec')?

Martin von Loewis wrote:
> This is tricky. I believe the only way to load a module from a string
> is by marshal.loads, which requires you to skip the magic first. In
> turn, this will give you a code object which you'll need to execute in
> a newly-created module's dictionary.

Hmm, plan B was to execute a compile(...) on the server using the source
code and ship a pickle of the result to the client. On the client, take
this codeobject and execute it into a module:

module = imp.new_module('MyModule')
sys.modules['MyModule'] = module
exec codepbject in vars(module)

Would this work? How efficient is it?

More hassles... ;-)

The idea is for the client to cache different versions of modules for
use when processing different jobs.

say module1 is created with:
module1 = imp.new_module('MyModule')
exec code1 in vars(module1)

...and module2 is created with:
module2 = imp.new_module('MyModule')
exec code2 in vars(module2)

...can I just swap them as follows?:
sys.modules['MyModule'] = module1
...create and use objects from MyModule...
sys.modules['MyModule'] = module2
...create and use objects from MyModule, hopefully using new code?...
...what happens to objects created from old MyModule code?...

More confusingly, what happens to objects created from classes in
MyModule that exist before and after swapping the module in sys.modules?

Head hurtingly yours,

Chris




More information about the Python-list mailing list