Converting functions

iu2 israelu at elbit.co.il
Mon Jan 24 04:19:40 EST 2011


On Jan 24, 9:51 am, Peter Otten <__pete... at web.de> wrote:
> iu2 wrote:
> > I'm trying to convert functions - pass a few functions to a converting
> > function, which change their behaviour and return the changed
> > functions:
>
> > >>> def cfuncs(*funcs):
> >         n = []
> >         for f in funcs:
> >                 def ff(*args, **key):
> >                         print 'Start!', f.func_name
> >                         res = f(*args, **key)
> >                         print 'End', f.func_name
> >                         return res
> >                 n.append(ff)
> >         return n
>
> > then I try it using two functions:
>
> > >>> def f1():
> >         print 'hello'
>
> > >>> def f2(x):
> >         return 2 * x
>
> > Eventually:
> > >>> newfuncs = cfuncs(f1, f2)
>
> > I would expect newfuncs to hold changed versions of f1 and f2, but
> > what is actually contained in newfuncs is twice the changed version of
> > f2.
>
> That is because the inner ff() references f which is a local variable of
> cfuncs(). By the time you invoke your newly created functions cfuncs() and
> thus the 'for f in funcs' loop has finished and the value of f is that of
> the last item in the funcs tuple. You can avoid the problem with another
> indirection
>
> def make_ff(f):
>     def ff(*args, **key):
>         print 'Start!', f.func_name
>         res = f(*args, **key)
>         print 'End', f.func_name
>         return res
>     return ff        
>
> def cfuncs(*funcs):
>     return [make_ff(f) for f in funcs]
>
> Peter- Hide quoted text -
>
> - Show quoted text -

Thanks!

I thought a function definition creates a closure around all used
vars.
As I understand now only variables that are passed as function
arguments can participate in a closure.



More information about the Python-list mailing list