Re: self modifying code
- From: Robin Becker <robin@xxxxxxxxxxxxxxxxxxx>
- Date: Sun, 30 Apr 2006 09:36:54 +0000
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
.
- References:
- self modifying code
- From: Robin Becker
- Re: self modifying code
- From: Ben C
- self modifying code
- Prev by Date: Re: Unpacking of query result
- Next by Date: Re: setting file permissions on a web server
- Previous by thread: Re: self modifying code
- Next by thread: opposite function to split?
- Index(es):
Relevant Pages
|