Re: self modifying code



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
.



Relevant Pages

  • Re: Whats the best way to iniatilize a function
    ... global DATA, _INITIALIZED ... def _close: ... I'm expecting Python to call it when ... even when the program exits. ...
    (comp.lang.python)
  • Re: Docorator Disected
    ... > def get_function(function): # Get func object off stack ... To understand decorator chains it is very helpfull to accept the ... def default: ... The function mul defines the inner functions default, ...
    (comp.lang.python)
  • Re: Name conflict in class hierarchy
    ... def func: ... print 'In B.func, calling A.f1' ... functionality, and I call the new function "func". ... you don't override existing methods in that class unintentionally. ...
    (comp.lang.python)
  • better scheduler with correct sleep times
    ... self.queue.put((fire_at, func, arg)) ... def runner: ... The scheduler goes to sleep for 10 seconds ...
    (comp.lang.python)
  • Re: Confessions of a Python fanboy
    ... Python functions and methods are first class objects. ... def factory_function: ... Python's model is consistent and simple: given a function "func", ...
    (comp.lang.python)