473,773 Members | 2,326 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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("newModul e.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 8321
qw******@yahoo. it schrieb:
[...]
Also Python can (writing and running a module, in-line):

fNew =open("newModul e.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("newModul e.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,global s(),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,global s(),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
9644
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. (e.g., a security-restricted version, or an interface implementation that doesn't require a filesystem.) One (common?) exception seems to occur in initialization. I understand stripping out arguments that your subclass explicitly handles or...
3
1897
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
2787
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 changing 'self' obviously just alters the value of that local variable. Is there some way for me to change the value of the BitSequence object itself? I've also tried wrapping and delegating using __getattr__, but I couldn't figure out how to handle...
5
1395
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 "self." prefix For example, in my brain I'm thinking: optc,args=getopt.getopt(args,cmdopts, cmdopts) but I'm having to type:
7
1910
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 = test.decode(self.qname)
24
2300
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 called as baseclass.methodname(self, <argument list>). 3. No need for declarations to disambiguate assignments to local/instance variables.
84
7223
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 use Ruby anywhere speed is not crucial especially for @ prefix is better- looking than self. But things grow -- is there any metaprogramming tricks or whatnot we can throw on the self? Cheers,
6
1814
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 does not work; I have to write self.val = SS.val and the same for the other members (as shown below). Is there a better way to do this? In the below self is part of a parse tree, F is the parse tree of a function f with argument x. If a node...
1
2105
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
1363
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
9621
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10264
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8937
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4012
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2852
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.