[Python-Help] imp.load_module from a string

Martin von Loewis loewis at informatik.hu-berlin.de
Mon Jul 10 07:03:37 EDT 2000


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

The first eight bytes are a magic signature. bytes[8:] is a marshalled
code object. Of course, a code object is an object, whereas the
contents of a pyc file is a string.

> 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?

Depends on how you transmit it. pickle does not support code objects;
marshal does. So I recommend to ship the pyc file, and unmarshal it.

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

It's better to write 'in module1.__dict__'

> ...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?...

To create and use objects, you don't have to put the module into
sys.modules; getattr(module,classname) would get you a class from the
module.

Apart from that, yes, that would work.

> ...what happens to objects created from old MyModule code?...

The objects stay the same. When the reference to the module is
release, class objects still remain as long as instance objects refer
to the class.

Regards,
Martin




More information about the Python-list mailing list