Re: self modifying code
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: self modifying code

From: Ben C <spamspam@spam.eggs>
Date: Sun Apr 30 2006 - 00:43:50 CEST

On 2006-04-29, Robin Becker <robin@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)
Received on Mon May 1 00:45:24 2006