self modifying code

taleinat at gmail.com taleinat at gmail.com
Mon May 1 10:04:26 EDT 2006


Yes, my implementation was less efficient because of the extra function
call.

> class Weird(object):
>         @staticmethod
>         def __call__(arg):
>                 data = 42
>                 def func(arg):
>                         return arg+data
>                 Weird.__call__ = staticmethod(func)
>                 return func(arg)
> c = Weird()

Ugh... you've used a class just like a function. You can't have two
different objects of this class, since you are overriding a static
method of the class! And you've hard-coded the data into the class
definition. Yes, it works, but I would never, ever trust such code to
someone else to maintain.

And you'll have to manually define such a class for every such
function. That's not very Pythonic.

Here's a reusable function that will define such a class for you, as
well as hide most of the ugliness (in fact, it supports -exactly- the
same interface as my previous implementation):

def InitializingFunction(func):
    class temp:
        @staticmethod
        def __call__(*args, **kw):
            temp.__call__ = staticmethod(func())
            return temp.__call__(*args, **kw)
    return temp()

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




More information about the Python-list mailing list