self modifying code

taleinat at gmail.com taleinat at gmail.com
Mon May 1 09:43:05 CEST 2006


First of all, the test can be optimized by adding a boolean flag which
indicates if the data has been initialized or not, and then just
testing a boolean value instead of doing an "is" comparison, at the
cost of an extra global variable. But this is still ugly (actually
uglier IMO).


I think this is a more Pythonic way to do it.
This class implements a function which initializes itself upon the
first call:

class InitializingFunction(object):
    def __init__(self, init):
        def initializer(*args, **kw):
            self.func = init()
            return self(*args, **kw)
        self.func = initializer
    def __call__(self, *args, **kw):
        return self.func(*args, **kw)

Now you can write your function almost exactly like you did before:

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

What have we gained from this? Two major advantages:
* no ugly 'global' statement
* no reliance on the function's name

And now you can easily create such functions forever using this class
to abstract away the ugly implementation ;)


Notice that since Function Decorators were introduced in Python2.4, you
can use InitializingFunction as a Decorator to achieve the same effect,
this time even without the need for a temporary name for a function:

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


And finally I must note that no matter which way you turn this around,
it will still be hard to read!




More information about the Python-list mailing list