Modifying func_closure

Bengt Richter bokr at oz.net
Mon Jul 12 14:19:07 EDT 2004


On 12 Jul 2004 18:55:24 +0300, Ville Vainio <ville at spammers.com> wrote:

>>>>>> "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

Another slant:

 >>> def make(a):
 ...     c = 33
 ...     g = dict(locals())
 ...     exec """\
 ... def update(delta):
 ...     global a,c
 ...     a += delta
 ...     return c,a
 ... """ in g
 ...     return g['update']
 ...
 >>> update = make(10)
 >>> update(3)
 (33, 13)
 >>> update(3)
 (33, 16)

 >>> f1,f2,f3 = [make(i) for i in [1,2,3]]
 >>> [f(0) for f in f1,f2,f3]
 [(33, 1), (33, 2), (33, 3)]
 >>> [f(100) for f in f1,f2,f3]
 [(33, 101), (33, 102), (33, 103)]
 >>> [f(0) for f in f1,f2,f3]
 [(33, 101), (33, 102), (33, 103)]

... enough fun break, gotta get back to other priorities ;-(

Regards,
Bengt Richter



More information about the Python-list mailing list