Loading new code...

Gordon McMillan gmcm at hypernet.com
Sun Aug 13 17:58:50 EDT 2000


Olivier Dagenais wrote: 

[Gordon thinks Olivier wants dynamic imports...]

>Sorry, I should have been more precise:  there's actual Python
>instructions in the database, not "compiled code objects"...  Does that
>make it easier? 

That depends on what you're actually doing. It's easier to get started.

>I get that idea from the documentation, saying a
>function or class definition must be "declared" before it is used (sort
>of like not using forward declarations in C), so, if I exec some code
>that has a class definition before I attempt to construct it, am I good
>to go?  For example: 
>
># open database
>cursor.execute ( "SELECT Instructions FROM Code" )
>for class_definition in cursor.fetchall ( ):
>    exec ( class_definition[0] )
>
>
>...so, knowing that I have just loaded [from the database] a class
>called, say, "Blarg", can I do:
>
>exec ( "self.aNewBlarg = Blarg ( 'arg1', 'arg2' )" )

Better than that. You can just say
  blarg = Blarg(arg1, arg2)

You exec'd that piece of code in your current namespace, so it injected new 
names there. Be very careful of the format of the strings you load from the 
DB; exec is not as forgiving as the interpreter.

>> 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).
>
>Understood.  So, assuming there are no "from X import ..." (or no
>"import ...", either), can I simply re-exec the class definition(s) that
>have been changed?  (reloading isn't THAT important, however loading
>arbitrary classes whose names are unknown is a priority)

Yes, and they'll clobber the existing names. However, existing instances of 
Blarg will still have the old Blarg definition.

If they're unknown names, you should probably look at passing exec a 
dictionary to use as a namespace, since that's easier to manage. You'll 
probably also want to use "apply" instead of exec'ing dynamically created 
code snippets to use the classes.

-Gordon



More information about the Python-list mailing list