Re: self modifying code



On 2006-04-29, Robin Becker <robin@xxxxxxxxxxxxxxxxxxx> wrote:
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 = somethingcomplexandcostly()
def func(a):
return simple(data,a)
return func(a)

It looks quite clever (a bit too clever ... :)

It could be replaced by

data = somethingcomplexandcostly()
def func(a):
return simple(data,a)

but this always calculates data.

Why not just:

data = None
def func(a):
global data

if not data:
data = somethingcomplexandcostly()

return simple(data, a)

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)
.



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)