import vs imp and friends.

E

Emanuele D'Arrigo

Greetings,

I was looking in the archive of this newsgroup and I found this
snippet:

import imp
sourcecode = 'def foo(x): return 11*x'
mod = imp.new_module('foo')
exec sourcecode in mod.__dict__
mod.foo(16)

Together with similar and sometimes more complete snippets available
they show how a module can be created out of string, plain text files
and compiled files. Neat!

Now the question. Apart from checking sys.module first and eventually
adding the new module to it if it isn't there already, and apart from
setting __file__, is there anything else that import does and this
snippet doesn't?

Manu
 
R

Robert Kern

Greetings,

I was looking in the archive of this newsgroup and I found this
snippet:

import imp
sourcecode = 'def foo(x): return 11*x'
mod = imp.new_module('foo')
exec sourcecode in mod.__dict__
mod.foo(16)

Together with similar and sometimes more complete snippets available
they show how a module can be created out of string, plain text files
and compiled files. Neat!

Now the question. Apart from checking sys.module first and eventually
adding the new module to it if it isn't there already, and apart from
setting __file__, is there anything else that import does and this
snippet doesn't?

Brett Cannon has a good presentation that covers basically the entirety of the
import mechanism:

http://us.pycon.org/2008/conference/schedule/event/12/

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
E

Emanuele D'Arrigo

Christian, Robert, thank you both for the replies, much appreciated.

Manu
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top