473,788 Members | 2,814 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
13 2133
ta******@gmail. com wrote:
.........

What have we gained from this? Two major advantages:
* no ugly 'global' statement
* no reliance on the function's name
I don't dispute either of the above, however, the actual overhead of
your approach appears to be much higher (see below) probably because it
has two function calls instead on one to get the answer.


And now you can easily create such functions forever using this class
to abstract away the ugly implementation ;)

........ yes indeed

######file dingo.py
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)

def init():
data = 42
def foo(arg):
return arg+data
return foo
a = InitializingFun ction(init)

def b(arg):
global b
data = 42
def b(arg):
return arg+data
return b(arg)
######

Testing with timeit
C:\Tmp>\Python\ lib\timeit.py -s"from dingo import a;a(0)" a(1)
100000 loops, best of 3: 2.25 usec per loop

C:\Tmp>\Python\ lib\timeit.py -s"from dingo import b;b(0)" b(1)
1000000 loops, best of 3: 0.52 usec per loop

so since the simple function is fairly trivial the overhead seems to be
around 4 times that of the weird approach.

The global naming stuff is pretty flaky and relies on the way names are
looked up; in particular it seems as though references to the original
global will be held at least throughout a single statement. If the first
call is "print b(0),b(1)" then b is initialised twice.

This 'masterpiece of obfuscation' ;) gets round that problem, but is
pretty odd to say the least and still relies on knowing the class name.

class Weird(object):
@staticmethod
def __call__(arg):
data = 42
def func(arg):
return arg+data
Weird.__call__ = staticmethod(fu nc)
return func(arg)
c = Weird()

it is still more expensive than b, but not by much

C:\Tmp>\Python\ lib\timeit.py -s"from dingo import c;c(1)" c(1)
1000000 loops, best of 3: 0.709 usec per loop

--
Robin Becker
May 1 '06 #11
Yes, my implementation was less efficient because of the extra function
call.
class Weird(object):
@staticmethod
def __call__(arg):
data = 42
def func(arg):
return arg+data
Weird.__call__ = staticmethod(fu nc)
return func(arg)
c = Weird()


Ugh... you've used a class just like a function. You can't have two
different objects of this class, since you are overriding a static
method of the class! And you've hard-coded the data into the class
definition. Yes, it works, but I would never, ever trust such code to
someone else to maintain.

And you'll have to manually define such a class for every such
function. That's not very Pythonic.

Here's a reusable function that will define such a class for you, as
well as hide most of the ugliness (in fact, it supports -exactly- the
same interface as my previous implementation) :

def InitializingFun ction(func):
class temp:
@staticmethod
def __call__(*args, **kw):
temp.__call__ = staticmethod(fu nc())
return temp.__call__(* args, **kw)
return temp()

@InitializingFu nction
def func():
data = somethingcomple xandcostly()
def foo(a):
return simple(data, a)
return foo

May 1 '06 #12
ta******@gmail. com wrote:
Yes, my implementation was less efficient because of the extra function
call.
class Weird(object):
@staticmethod
def __call__(arg):
data = 42
def func(arg):
return arg+data
Weird.__call__ = staticmethod(fu nc)
return func(arg)
c = Weird()


ugh indeed
Ugh... you've used a class just like a function. You can't have two
different objects of this class, since you are overriding a static
method of the class! And you've hard-coded the data into the class
definition. Yes, it works, but I would never, ever trust such code to
someone else to maintain.

And you'll have to manually define such a class for every such
function. That's not very Pythonic.
no arguments here


Here's a reusable function that will define such a class for you, as
well as hide most of the ugliness (in fact, it supports -exactly- the
same interface as my previous implementation) :

def InitializingFun ction(func):
class temp:
@staticmethod
def __call__(*args, **kw):
temp.__call__ = staticmethod(fu nc())
return temp.__call__(* args, **kw)
return temp()

@InitializingFu nction
def func():
data = somethingcomple xandcostly()
def foo(a):
return simple(data, a)
return foo


I already tried this kind of factory function, but in fact I think the
original global test version outperforms even the statically coded Weird
class.

ie
data = None
def d(arg):
global data
if data is None:
data = 42
return arg+data

@InitializingFu nction
def e():
data = 43
def foo(a):
return data+a
return foo

are both better than any except the global function replacement nonsense

C:\Tmp>\Python\ lib\timeit.py -s"from dingo import d;d(0)" d(1)
1000000 loops, best of 3: 0.556 usec per loop

C:\Tmp>\Python\ lib\timeit.py -s"from dingo import e;e(0)" e(1)
1000000 loops, best of 3: 1.09 usec per loop

but the structured approach is still twice as slow as the simplistic one :(
--
Robin Becker
May 1 '06 #13
Personally, I would almost always pay the x2 efficiency price in order
to use a class. But then I don't know what you're writing.

Of course, if you really need it to be efficient, you can write it as a
C extension, or use Pyrex, etc. and get -much- better results.

May 1 '06 #14

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

Similar topics

16
8147
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
8324
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
4283
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
2287
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
4824
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
5156
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
2641
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
9656
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
9967
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...
1
7517
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
6750
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
5399
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
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4070
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
3674
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.