Self-modifying Code

Peter Hansen peter at engcorp.com
Thu May 19 15:34:08 EDT 2005


qwweeeit at yahoo.it wrote:
[regarding "self-modifying code"]
> fNew =open("newModule.py",'w')
> lNew=['print 123\n','print 454\n','print 789\n']
> fNew.writelines(lNew)
> fNew.close()
> from newModule import *

This isn't really self-modifying code (unless you are talking about this 
being a small part of a much larger application which is where the 
import actually occurs), but in any event neither is it the simplest way 
to do what you are trying to do using Python.  The absolute simplest, 
which is largely equivalent to what you've done here, is simply "exec 
'print 123\nprint 456\nprint 789'".  A close relative is the method 
provided by the execfile() standard function (avoiding the import).

> Did you know? Certainly someone has already discovered and applied
> that, because the applications are several (think only to the
> possibility of reducing code length by eliminating the coding of false
> alternatives, or the possibility to convert a list of instructions
> taken somewhere in a running code...)

Those same applications are better served, generally, by doing things 
like parameterizing function definitions on-the-fly, or by dynamically 
binding new methods into objects or classes.  There are many recipes in 
the CookBook or the list archives showing how to do all these sorts of 
things.

I'm afraid the technique you show above, while intriguing to a newcomer 
to Python, has a limited number of use cases, though if one needs to 
modify or generate some small part of a program for later use (requiring 
the basic persistence that your technique has), it is definitely a 
viable technique.

-Peter



More information about the Python-list mailing list