Converting functions

Peter Otten __peter__ at web.de
Mon Jan 24 02:51:24 EST 2011


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



More information about the Python-list mailing list