Re: self modifying code



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


John

.



Relevant Pages

  • Re: self modifying code
    ... def func: ... The use of global func is just plain weird :-) ... this doesn't work because you can add attributes to plain object instances: ...
    (comp.lang.python)
  • Re: self modifying code
    ... modifying code was dangerous. ... def func: ... global func, data ... from lazymodule import func ...
    (comp.lang.python)
  • Re: Passing function objects to timeit
    ... def test_timer(func1, func2): ... global gFUNC ...
    (comp.lang.python)
  • self modifying code
    ... When young I was warned repeatedly by more knowledgeable folk that self modifying code was dangerous. ... def func: ... global func, data ...
    (comp.lang.python)