self modifying code

Peter Otten __peter__ at web.de
Sat Apr 29 13:36:12 EDT 2006


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





More information about the Python-list mailing list