Modifying func_closure

Peter Otten __peter__ at web.de
Mon Jul 12 18:44:40 CEST 2004


Ville Vainio 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 :-).

It's a small step from the ubiquitous list to the more readable Bunch, so I
expect others have been there before.
 
> 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.
 
Nothing that I know of. With the globals() dictionary you could do

class Bunch:
    def __init__(self, d):
        self.__dict__ = d
# ...
    outer = Bunch(globals())
# ...

but this doesn't work with locals() which seem to be a snapshot:

>>> def f():
...     d = locals()
...     print d
...
>>> f()
{} # no 'd'


Peter





More information about the Python-list mailing list