[Tutor] Modifying Source Code while Program is Running

Alan Gauld alan.gauld at freenet.co.uk
Thu Nov 24 22:08:21 CET 2005


There are many ways of doing this, few of them very nice IMHO.

> without having to restart the program?  Is it feasible to get a
> program to change it's own source code while it is running?

Yes, you can overwrite an existing module then call reload 
from within the program.

> For example, if you have a web server such as CherryPy that will
> (hopefully) be running for months at a time and you want to be able to
> change classes without having to restart the server.  

Yes that would be feasible., preferrably in response to an admin
page where you could fill in a list of modules to be reloaded...
But you neeed to be very careful not to break any of the interfaces, 
the Liskov Substitution Principle must be strictly observed.

> to allow users of the site to edit a class through the web and 
> see the changes to the site immediately?

Extremely dangerous but the same principle would apply, 
simply load the existing module into an editor pane then save 
the modified version and reload it.

> Can a python program change a class, 

Yes as above.

> change all the objects already created by that class 

Trickier and potentially involves some low level poking that 
should not be encouraged IMHO! :-)

> and save the modified class definition, so that
> if the program were restarted it would return to exactly the same
> state? (assuming all objects were saved to a database or somesuch).

If the LSP is adhered to its feasible but I don't intend to try any 
such thing! It would be full of pitfalls and an almosyt certain recipe 
for reliability problems that would be impossible to find.
Self modifying code sounds like a good idea but there is a very 
good reason why its almost never used in production software!

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list