Loading new code...

Gordon McMillan gmcm at hypernet.com
Fri Aug 11 20:43:12 EDT 2000


Olivier Dagenais wrote: 

>I'm storing code in a database.  I'd like to be able to import the code
>in the global namespace (well, so that I only need to import/load it
>once, and "everybody" can see it), but "from module_name import *" will
>try to read from a file... (which I don't have, and don't feel like
>creating, otherwise that would defeat the purpose of having a database)

What you're trying to do can't be done, because there is no "global" 
namespace. If you have 2 modules that both want to see module X, they both 
must "import X". Only one of those imports will involve any actual work, 
the second one will just gain access to the already imported module 
(through sys.modules).

>So, as suggested in the documentation, I looked up the imp module.. 
>Would the load_module function do what I want it to, or should I just
>"exec" the block of code I retrieve from the database?  What would be
>the most elegant method, while still allowing me to reload the code by
>updating and re-querying the database at a later time?

You want to use ihooks or imputil (Greg Stein's module on lyra.org). You'll 
probably find the latter easier to use. The imp module really only gives 
you access to some low level routines in the import process. There's a lot 
more than goes on than just getting the code object. (And what you actually 
want to do at the bottom level is unmarshal a compiled code object, not 
exec it.)

But reloading a module is another can of worms. For one thing, reloading 
does no good unless everyone is accessing the module through the module 
object (IOW, one "from X import ..." and you're screwed).

- Gordon



More information about the Python-list mailing list