473,774 Members | 2,275 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

self modifying code

When young I was warned repeatedly by more knowledgeable folk that self
modifying code was dangerous.

Is the following idiom dangerous or unpythonic?

def func(a):
global func, data
data = somethingcomple xandcostly()
def func(a):
return simple(data,a)
return func(a)

It could be replaced by

data = somethingcomple xandcostly()
def func(a):
return simple(data,a)

but this always calculates data.
--
Robin Becker
Apr 29 '06 #1
13 2131
Robin Becker schrieb:
When young I was warned repeatedly by more knowledgeable folk that self
modifying code was dangerous.

Is the following idiom dangerous or unpythonic?

def func(a):
global func, data
data = somethingcomple xandcostly()
def func(a):
return simple(data,a)
return func(a)
It took me quite a while to figure out how it works, so, yes, I'd say
it's unpythonic ;-). It's not really dangerous, but it can get nasty if
someone tries to rename the function, or put it into a class.

But that's probably not the kind of "self-modifying code" you've been
warned against anyway: I've only ever seen self-modifying code in
assembly language or in lisp, the idea is that you really change the
code (i.e. single opcodes in the function that's currently running), so
you can e.g. make an infinite loop, and eventually overwrite the loop
statement to do something else so the loop ends. I'm not sure if you
can do the same thing in Python, maybe by changing the bytecode of a
running function.
It could be replaced by

data = somethingcomple xandcostly()
def func(a):
return simple(data,a)

but this always calculates data.


You could of course initialize data with None and calculate it only on
demand. Or you could use:
http://www.phyast.pitt.edu/~micheles...n.html#memoize
This has the advantage of encapsulating the memoization logic so it can
be tested (and understood) separately from your code.

Apr 29 '06 #2
Robin Becker wrote:
When young I was warned repeatedly by more knowledgeable folk that self
modifying code was dangerous.

Is the following idiom dangerous or unpythonic?

def func(a):
global func, data
data = somethingcomple xandcostly()
def func(a):
return simple(data,a)
return func(a)

It could be replaced by

data = somethingcomple xandcostly()
def func(a):
return simple(data,a)

but this always calculates data.


Consider

data = None
def func(a):
global data
if data is None:
data = costly()
return simple(data, a)

if you want lazy evaluation. Not only is it easier to understand,
it also works with

from lazymodule import func

at the cost of just one object identity test whereas your func()
implementation will do the heavy-lifting every time func() is called in the
client (unless func() has by chance been invoked as lazymodule.func ()
before the import).

Peter
Apr 29 '06 #3
Peter Otten wrote:
.....

def func(a):
global func, data
data = somethingcomple xandcostly()
def func(a):
return simple(data,a)
return func(a)
.........
at the cost of just one object identity test whereas your func()
implementation will do the heavy-lifting every time func() is called in the
client (unless func() has by chance been invoked as lazymodule.func ()
before the import).


in the example code the heavy lifting, costly(), is done only once as
the function that does it is overwritten. As pointed out it won't work
as simply in a class. Memoisation could improve the performance of the
normal case form of the function ie

def func(a):
return simple(data,a)

but I guess that would depend on whether simple(data,a) is relatively
expensive compared to the costs the memo lookup.
--
Robin Becker
Apr 29 '06 #4
Robin Becker <ro***@NOSPAMre portlab.com> writes:
When young I was warned repeatedly by more knowledgeable folk that self
modifying code was dangerous.

Is the following idiom dangerous or unpythonic?

def func(a):
global func, data
data = somethingcomple xandcostly()
def func(a):
return simple(data,a)
return func(a)


1. I don't think most people would call that "self-modifying code". I
won't try defining that term precisely because I know you'll just
pick holes in my definition ;-)

2. The use of global func is just plain weird :-)

3. Peter Otten's version is OK, but how about this, using a closure
instead of globals (UNTESTED)

def make_func():
namespace = object()
namespace.data = None
def func(a):
if namespace.data is None:
namespace.data = somethingcomple xandcostly()
return simple(namespac e.data, a)
return func
func = make_func()
John

Apr 29 '06 #5
John J. Lee wrote:
1. I don't think most people would call that "self-modifying code". I
won't try defining that term precisely because I know you'll just
pick holes in my definition ;-)

Don't really disagree about the rewriting code, but the function does
re-define itself.

2. The use of global func is just plain weird :-)

3. Peter Otten's version is OK, but how about this, using a closure
instead of globals (UNTESTED)

def make_func():
namespace = object()
namespace.data = None
def func(a):
if namespace.data is None:
namespace.data = somethingcomple xandcostly()
return simple(namespac e.data, a)
return func
func = make_func()

........
the inner function is almost precisely what I started with, except I
used the global namespace. However, it keeps the test in side the
function which costs about 1%.
--
Robin Becker
Apr 29 '06 #6
On 2006-04-29, Robin Becker <ro***@NOSPAMre portlab.com> wrote:
When young I was warned repeatedly by more knowledgeable folk that self
modifying code was dangerous.

Is the following idiom dangerous or unpythonic?

def func(a):
global func, data
data = somethingcomple xandcostly()
def func(a):
return simple(data,a)
return func(a)
It looks quite clever (a bit too clever ... :)
It could be replaced by

data = somethingcomple xandcostly()
def func(a):
return simple(data,a)

but this always calculates data.


Why not just:

data = None
def func(a):
global data

if not data:
data = somethingcomple xandcostly()

return simple(data, a)

Or nicer to use a "singleton" perhaps than a global, perhaps something
like this:

class Func(object):
exists = False

def __init__(self):
assert not Func.exists
Func.exists = True

self.data = None

def simple(self, a):
assert self.data is not None
# ... do something with self.data presumably
return something

def __call__(self, a):
if self.data is None:
self.data = somethingcomple xandcostly()
return self.simple(a)

func = Func()

func(a)
Apr 29 '06 #7
John J. Lee wrote:
Robin Becker <ro***@NOSPAMre portlab.com> writes:
When young I was warned repeatedly by more knowledgeable folk that self
modifying code was dangerous.

Is the following idiom dangerous or unpythonic?

def func(a):
global func, data
data = somethingcomple xandcostly()
def func(a):
return simple(data,a)
return func(a)


1. I don't think most people would call that "self-modifying code". I
won't try defining that term precisely because I know you'll just
pick holes in my definition ;-)

2. The use of global func is just plain weird :-)

3. Peter Otten's version is OK, but how about this, using a closure
instead of globals (UNTESTED)

def make_func():
namespace = object()
namespace.data = None
def func(a):
if namespace.data is None:
namespace.data = somethingcomple xandcostly()
return simple(namespac e.data, a)
return func
func = make_func()


Unfortunately, this doesn't work because you can add attributes to plain
object instances:
namespace = object()
namespace.data = None Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
AttributeError: 'object' object has no attribute 'data'

Maybe you want something like:
def make_func(): .... def func(a):
.... if func.data is None:
.... func.data = somethingcomple xandcostly()
.... return simple(func.dat a, a)
.... func.data = None
.... return func
.... func = make_func()
def somethingcomple xandcostly(): .... print 'executing somethingcomple xandcostly'
.... return 42
.... def simple(data, a): .... return data, a
.... func(1) executing somethingcomple xandcostly
(42, 1) func(2)

(42, 2)

STeVe
Apr 29 '06 #8
Ben C wrote:
........

Why not just:

data = None
def func(a):
global data

if not data:
data = somethingcomple xandcostly()

return simple(data, a)

well in the original instance the above reduced to something like

data=None
def func(arg):
global data
if data:
data = ......
return ''.join(map(dat a.__getitem__,a rg))

so the actual function is pretty low cost, but the extra cost of the
test is actually not very significant, but if the actual function had
been cheaper eg

def func(arg):
global data
if data is None:
data = ....
return data+arg

then the test is a few percent of the total cost; why keep it?

All the other more complex solutions involving namespaces, singletons
etc seem to add even more overhead.
Or nicer to use a "singleton" perhaps than a global, perhaps something
like this:

class Func(object):
exists = False

def __init__(self):
assert not Func.exists
Func.exists = True

self.data = None

def simple(self, a):
assert self.data is not None
# ... do something with self.data presumably
return something

def __call__(self, a):
if self.data is None:
self.data = somethingcomple xandcostly()
return self.simple(a)

func = Func()

func(a)

--
Robin Becker
Apr 30 '06 #9
First of all, the test can be optimized by adding a boolean flag which
indicates if the data has been initialized or not, and then just
testing a boolean value instead of doing an "is" comparison, at the
cost of an extra global variable. But this is still ugly (actually
uglier IMO).
I think this is a more Pythonic way to do it.
This class implements a function which initializes itself upon the
first call:

class InitializingFun ction(object):
def __init__(self, init):
def initializer(*ar gs, **kw):
self.func = init()
return self(*args, **kw)
self.func = initializer
def __call__(self, *args, **kw):
return self.func(*args , **kw)

Now you can write your function almost exactly like you did before:

def init():
data = somethingcomple xandcostly()
def foo(a):
return simple(data, a)
return foo
func = InitializingFun ction(init)

What have we gained from this? Two major advantages:
* no ugly 'global' statement
* no reliance on the function's name

And now you can easily create such functions forever using this class
to abstract away the ugly implementation ;)
Notice that since Function Decorators were introduced in Python2.4, you
can use InitializingFun ction as a Decorator to achieve the same effect,
this time even without the need for a temporary name for a function:

@InitializingFu nction
def func():
data = somethingcomple xandcostly()
def foo(a):
return simple(data, a)
return foo
And finally I must note that no matter which way you turn this around,
it will still be hard to read!

May 1 '06 #10

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

Similar topics

16
8144
by: Japcuh | last post by:
How do you write self modifying code in Java? Japcuh (Just Another Perl C Unix Hacker) http://www.catb.org/~esr/faq/hacker-howto.htm#what_is ..0. ...0 000
6
8321
by: qwweeeit | last post by:
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= fNew.writelines(lNew) fNew.close()
2
4282
by: Joel Jose | last post by:
agreed the 'mutation engine' by dark avenger was a real deadly master-code piece.., but then.. if one could create a self mutating code..in real time then i think it would just b the most technical advancement of this century!!! just think... instead of those nagging.. and more irritating than helpfull death screen(error logs).. that windows shows every other time.. if it could evolve itself to cope up with the error.. if the pe...
18
2285
by: Ralf W. Grosse-Kunstleve | last post by:
My initial proposal (http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html) didn't exactly get a warm welcome... And Now for Something Completely Different: class autoinit(object): def __init__(self, *args, **keyword_args): self.__dict__.update(
12
4823
by: AES | last post by:
Can an HTML web page dynamically modify its own code? (without resort to Java or any other non-HTML complexities) That is, is there any provision in HTML such that a single "Next" button on a main or index.html page will: a) Change an image displayed on that page (say Picture_1.jpg) to the next image in a sequence (say Picture_2.jpg), AND
10
5155
by: jon | last post by:
I am a beginner C programmer, this is actually my first programming lanugage, besides html, cgi, and javascript. I am looking for a way to make an .exe file, or a copy of my own file. I have tried writing a file, compling it, and reading it in a notepad, then writing a program to write it again, but i have had no luck. I assure you i'm not trying to create the next big virus, or worm, but only trying to expaned my knowledge on what...
5
2640
by: IUnknown | last post by:
Ok, we are all aware of the situation where modifying the folder structure (adding files, folders, deleting files, etc) will result in ASP.NET triggering a recompilation/restart of the application. In a nutshell, I understand how this can be considered desireable by some, but I am not one of those people. My situation is that we have a root site (hosted @ http://www.mydomain.com) in the root application folder '/'.
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
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10039
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
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
6717
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
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
2
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.