Re: self modifying code



John J. Lee wrote:
Robin Becker <robin@xxxxxxxxxxxxxxxxxxx> writes:

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)

1. I don't think most people would call that "self-modifying code". I
won't try defining that term precisely because I know you'll just
pick holes in my definition ;-)

2. The use of global func is just plain weird :-)

3. Peter Otten's version is OK, but how about this, using a closure
instead of globals (UNTESTED)

def make_func():
namespace = object()
namespace.data = None
def func(a):
if namespace.data is None:
namespace.data = somethingcomplexandcostly()
return simple(namespace.data, a)
return func
func = make_func()

Unfortunately, this doesn't work because you can add attributes to plain object instances:

>>> namespace = object()
>>> namespace.data = None
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: 'object' object has no attribute 'data'

Maybe you want something like:

>>> def make_func():
.... def func(a):
.... if func.data is None:
.... func.data = somethingcomplexandcostly()
.... return simple(func.data, a)
.... func.data = None
.... return func
....
>>> func = make_func()
>>> def somethingcomplexandcostly():
.... print 'executing somethingcomplexandcostly'
.... return 42
....
>>> def simple(data, a):
.... return data, a
....
>>> func(1)
executing somethingcomplexandcostly
(42, 1)
>>> func(2)
(42, 2)

STeVe
.



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: self modifying code
    ... modifying code was dangerous. ... def func: ... global func, data ... from lazymodule import func ...
    (comp.lang.python)