Modifying func_closure

Ville Vainio ville at spammers.com
Mon Jul 12 11:55:24 EDT 2004


>>>>> "Peter" == Peter Otten <__peter__ at web.de> writes:

    Peter> Now let's change the misleading name 'self' into 'outer':

--------------

class Bunch:
    def __init__(self, kw):
        self.__dict__.update(kw)


def make(a):
    c = 33
    outer = Bunch(locals())
    def update(self, delta):
            outer.a += delta
            return outer.c, outer.a
    return update

class Foo:
    update = make(20)

print Foo().update(99)

--------------

    Peter> There you are. 

Nice hack. Put it somewhere, if it's not somewhere already :-).

Any way to make the 'outer' class really access the locals of the
function, so that every closure produced by the function (if it didn't
return it, but exposed it e.g. by passing it as an argument to
something) would refer to the real variables in function? The Bunch
approach takes a copy, so if you manipulate locals after instantiate
the closure the manipulations would not be visible to the closure.

-- 
Ville Vainio   http://tinyurl.com/2prnb



More information about the Python-list mailing list