self modifying code

Ben C spamspam at spam.eggs
Sat Apr 29 18:43:50 EDT 2006


On 2006-04-29, Robin Becker <robin at NOSPAMreportlab.com> 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 looks quite clever (a bit too clever ... :)

> It could be replaced by
>
> data = somethingcomplexandcostly()
> def func(a):
>      return simple(data,a)
>
> but this always calculates data.

Why not just:

data = None
def func(a):
    global data

    if not data:
        data = somethingcomplexandcostly()

    return simple(data, a)

Or nicer to use a "singleton" perhaps than a global, perhaps something
like this:

class Func(object):
    exists = False

    def __init__(self):
        assert not Func.exists
        Func.exists = True

        self.data = None

    def simple(self, a):
        assert self.data is not None
        # ... do something with self.data presumably
        return something

    def __call__(self, a):
        if self.data is None:
            self.data = somethingcomplexandcostly()
        return self.simple(a)

func = Func()

func(a)



More information about the Python-list mailing list