Re: self modifying code
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: self modifying code

From: Robin Becker <robin@NOSPAMreportlab.com>
Date: Sun Apr 30 2006 - 11:36:54 CEST

Ben C wrote:
.......
>
> Why not just:
>
> data = None
> def func(a):
> global data
>
> if not data:
> data = somethingcomplexandcostly()
>
> 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(data.__getitem__,arg))

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 = somethingcomplexandcostly()
> return self.simple(a)
>
> func = Func()
>
> func(a)

-- 
Robin Becker
Received on Mon May 1 00:46:56 2006