Re: self modifying code



Robin Becker schrieb:

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 took me quite a while to figure out how it works, so, yes, I'd say
it's unpythonic ;-). It's not really dangerous, but it can get nasty if
someone tries to rename the function, or put it into a class.

But that's probably not the kind of "self-modifying code" you've been
warned against anyway: I've only ever seen self-modifying code in
assembly language or in lisp, the idea is that you really change the
code (i.e. single opcodes in the function that's currently running), so
you can e.g. make an infinite loop, and eventually overwrite the loop
statement to do something else so the loop ends. I'm not sure if you
can do the same thing in Python, maybe by changing the bytecode of a
running function.

It could be replaced by

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

but this always calculates data.

You could of course initialize data with None and calculate it only on
demand. Or you could use:
http://www.phyast.pitt.edu/~micheles/python/documentation.html#memoize
This has the advantage of encapsulating the memoization logic so it can
be tested (and understood) separately from your code.

.



Relevant Pages

  • Re: Just wondering
    ... If the task is to test the overhead, then the two loops need to be equivalent. ... compare map() time to for time, ... def doit: ... Doing the loop tells what it takes to loop. ...
    (comp.lang.python)
  • Re: Start and stop a ruby loop ;(
    ... def bar ... Because the object's instance variables of @baz and @quux haven't been ... it looks like you want to use a while loop instead of a for ... class MyFirstClass ...
    (comp.lang.ruby)
  • Re: Another TCPSocket Question
    ... require 'socket' ... puts "Entering loop" ... def initialize(tcp_sock) ... not shown here is required to deal with binary networking streams ...
    (comp.lang.ruby)
  • Re: Style question - defining immutable class data members
    ... def inc: ... This is about a small optimization in defining ... Each one creates its own count, and a list variables, and manipulates them calls to inc and val. ... The values manipulated by one instance of C2 in one pass through the loop are not affected when, on the next pass through the loop, that instance is destroyed and another instance is created. ...
    (comp.lang.python)
  • Re: Style question - defining immutable class data members
    ... The only difference between Case1 and Case2 classes is where the count ... on is discarded as you go through the next pass on the outer loop. ... def inc: ...
    (comp.lang.python)