[mod_python] Udate python modules without restarting Apache

Nicolas Lehuen nicolas at lehuen.com
Thu Oct 14 12:32:05 EDT 2004


 

> -----Message d'origine-----
> De : Graham Dumpleton [mailto:grahamd at dscpl.com.au] 
> Envoyé : jeudi 14 octobre 2004 04:42
> À : Nicolas Lehuen
> Cc : mod_python at modpython.org
> Objet : Re: [mod_python] Udate python modules without 
> restarting Apache
> 
> 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)
> 

Ok, thanks for the tip, Graham.

I thought about using new.module(), but there was no information about it
tinkering with sys.modules (though it seemed that it did not). I didn't see
imp.new_module().

Having a look at new.module, it seems that new.module == types.ModuleType ==
type(sys). So a call to new.module is basically an instanciation of the
module class. imp.new_module() is natively implemented :

static PyObject *
imp_new_module(PyObject *self, PyObject *args)
{
	char *name;
	if (!PyArg_ParseTuple(args, "s:new_module", &name))
		return NULL;
	return PyModule_New(name);
}

So I guess those two function do exactly the same thing. I'll modify my
ModuleCache to use imp.new_module instead of a fake Module object.

Regards,

Nicolas




More information about the Mod_python mailing list