473,320 Members | 2,202 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Self-modifying Code

Hi all,

when I was young I programmed in an interpreted language that allowed
to modify itself.
Also Python can (writing and running a module, in-line):

fNew =open("newModule.py",'w')
lNew=['print 123\n','print 454\n','print 789\n']
fNew.writelines(lNew)
fNew.close()
from newModule import *

Running this small example it correctly displays:
123
456
789

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...)

Bye.

Jul 19 '05 #1
6 8275
qw******@yahoo.it schrieb:
[...]
Also Python can (writing and running a module, in-line):

fNew =open("newModule.py",'w')
lNew=['print 123\n','print 454\n','print 789\n']
fNew.writelines(lNew)
fNew.close()
from newModule import *
[...]


You don't even need a file for this.
Try: exec("print 123; print 456; print 789")

Bye,
Dennis
Jul 19 '05 #2
qw******@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
Jul 19 '05 #3
Hi, you, also !

A view, with a little difference :
def titi(par):
if par>222:
return par*2
else:
return par*10

print titi(123)
print titi(1234)

#now, change the function, "on instant"
txt="""def titi(par):
if par>222:
return str(par)*2
else:
return str(par)*5
"""
exec(txt,globals(),globals())

print titi(123)
print titi(1234)


Michel Claveau

Jul 19 '05 #4
On Thu, 19 May 2005 21:49:46 +0200, Do Re Mi chel La Si Do wrote:
Hi, you, also !

A view, with a little difference :
def titi(par):
if par>222:
return par*2
else:
return par*10

print titi(123)
print titi(1234)

#now, change the function, "on instant"
txt="""def titi(par):
if par>222:
return str(par)*2
else:
return str(par)*5
"""
exec(txt,globals(),globals())

print titi(123)
print titi(1234)

Self-modifying code is almost always a TERRIBLE idea. Using exec is
dangerous unless you can control what is being executed. Using exec on
code a user supplies is a huge security hole.

Self-modifying code is one of those ideas that seems cute when you first
learn about it, but in practice is a bad idea. It makes debugging your
code much more difficult. It makes comprehending how your code works
harder. Generally, you should avoid it, and shun code that modifies itself.

Having said that, here is a good example of self-modifying code:

http://aspn.activestate.com/ASPN/Coo...n/Recipe/68429

The RingBuffer class dynamically modifies itself once it is full so that
its behaviour changes.
--
Steven

Jul 19 '05 #5
Hi !
I often use the auto-modification of code, to allow the users to adapt
software to the evolution of their needs.

When this technique is controlled, and framed well, it presents only few
problems.

AMHA, to speak about danger, it is the result of a lack of practice and
tests. It is a little the same debate as: dynamic language versus static
language.
@-salutations

Michel Claveau


Jul 19 '05 #6
Steven D'Aprano a écrit :
(snip)
Having said that, here is a good example of self-modifying code:

http://aspn.activestate.com/ASPN/Coo...n/Recipe/68429

The RingBuffer class dynamically modifies itself once it is full so that
its behaviour changes.


This is nothing more than a pythonic implementation of the state
pattern. I would not call this "self-modifying code", since the code
itself is not modified.

Jul 19 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Jim Jewett | last post by:
Normally, I expect a subclass to act in a manner consistent with its Base classes. In particular, I don't expect to *lose* any functionality, unless that was the whole point of the subclass. ...
3
by: Max M | last post by:
# -*- coding: latin-1 -*- """ I subclass datetime and timedelta >>> dt = myDatetime(1970,1,1) >>> type(dt) <class 'dtime.myDatetime'>
4
by: David Coffin | last post by:
I'd like to subclass int to support list access, treating the integer as if it were a list of bits. Assigning bits to particular indices involves changing the value of the integer itself, but...
5
by: Mark Harrison | last post by:
Is there a way to do something equivalent to "import * from self"? Perhaps I'm doing something wrong, but I'm having a headache when dealing with class instance data, forgetting to always put the...
7
by: Andrew Robert | last post by:
Hi Everyone, I am having a problem with a class and hope you can help. When I try to use the class listed below, I get the statement that self is not defined. test=TriggerMessage(data) var...
24
by: Peter Maas | last post by:
The Python FAQ 1.4.5 gives 3 reasons for explicit self (condensed version): 1. Instance variables can be easily distinguished from local variables. 2. A method from a particular class can be...
84
by: braver | last post by:
Is there any trick to get rid of having to type the annoying, character-eating "self." prefix everywhere in a class? Sometimes I avoid OO just not to deal with its verbosity. In fact, I try to...
6
by: Bart Kastermans | last post by:
I am playing with some trees. In one of the procedures I wrote for this I am trying to change self to a different tree. A tree here has four members (val/type/left/right). I found that self = SS...
1
by: lpyth | last post by:
class abc: def __init__(self,x,y,z): self.x = x self.y = y self.z = z def add(self): c = self.x + self.y + self.z
3
by: Aaron Gray | last post by:
Regarding 'self' :- if (self) document.write( "self<br>"); if (self === window) document.write( "self === window<br>"); else if (self == window) document.write( "self == window<br>");
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.