En Wed, 12 Mar 2008 18:02:54 -0200, Jean-Paul Calderone
Hi all. I've got a python file called 'foo' (no extension). I want to
be able to load it as a module, like so:
m = __import__('foo')
You can use execfile:
foo = {}
execfile('foo', foo)
Apart from the different syntax in accessing the module globals
(attributes with __import__ (foo.x) vs dict entries with execfile
(foo['x'])), there are probably more subtle differences but I can't
tell for sure. It would be nice if someone more knowledgeable can
compare and contrast these two appraches.
Another difference is that when you import a module, its code is
(usually)
only executed once. Each import after the first just returns a reference
to the already-created module object. When you use execfile, the code is
re-evaluated each time.
The steps done by import are outlined in this message
http://groups.google.com/group/comp...adc39ac/3882ce35f13ff971#msg_96a590bca5f2be8c
The relevant part (citing myself):
newmodule = sys.modules[modulename] = ModuleType(modulename)
# constructor sets __name__ and a null __doc__
newmodule.__builtins__ = current builtins
newmodule.__file__ = filename
code = read from filename and compile it
exec code in newmodule.__dict__
Apart from sys.modules and __file__, there is another difference, the
__builtins__ attribute. It is important: if not present, Python executes
the code in "safe mode" where certain operations are disabled (and there
is a big performance penalty).