Graham Dumpleton
grahamd at dscpl.com.au
Wed Oct 13 21:42:10 EDT 2004
On Oct 10 18:50, Graham Dumpleton <grahamd at dscpl.com.au> wrote: > > When using combination of imp.find_module() and imp.load_module(), main > thing is that it is a true module. Ie., result of calling type() on the > result will actually be <type 'module'>. > > Taking a simple module which contains: > > variable = 0 > def function(): pass > > If this module is imported using imp.load_module(), result is same as > "import" and running dir() on the module yields the following. > > ['__builtins__', '__doc__', '__file__', '__name__', 'function', > 'variable'] > > If one uses execfile() however, the result is simply a dictionary, ie., > type() yields <type 'dict'>. The results of calling keys() on that > dictionary yields the following. > > ['__builtins__', 'variable', 'function'] > > In terms of executing code within the context of the two, there > probably isn't going to be much difference. The only issue would > be if the code being loaded had expected it to be executing > within the environment of a true module. Ie., that it expected > __file__ and __name__ to actually exist. FWIW, if using execfile() I have since found that it is probably better to use: import imp module = imp.new_module("z") module.__file__ = "z.py" execfile("z.py",module.__dict__) That way, executing type() on the module gives <type 'module'> and thus things one expects to work on modules will. The imp.new_module() method does not result in the module being listed in sys.modules. -- Graham Dumpleton (grahamd at dscpl.com.au)
|