self modifying code

nikie n.estner at gmx.de
Sat Apr 29 13:31:31 EDT 2006


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.




More information about the Python-list mailing list