Re: self modifying code



Robin Becker 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 could be replaced by

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

but this always calculates data.

Consider

data = None
def func(a):
global data
if data is None:
data = costly()
return simple(data, a)

if you want lazy evaluation. Not only is it easier to understand,
it also works with

from lazymodule import func

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

Peter


.



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