Re: self modifying code



Peter Otten wrote:
.....

def func(a):
global func, data
data = somethingcomplexandcostly()
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
.



Relevant Pages

  • 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)
  • Re: optimization
    ... Neal> def something: ... Neal> It appears that if Func is called many times, ... If the inner function is constant and does not directly access outer function locals, and if every last tick of speed is a concern, then it can be move out and given a name like _outer_helper. ...
    (comp.lang.python)