Converting functions

iu2 israelu at elbit.co.il
Mon Jan 24 02:02:25 EST 2011


Hi all,

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:

>>> newfuncs[1](100)
Start! f2
End f2
200

which is what I expected,

but:

>>> newfuncs[0]()
Start! f2

Traceback (most recent call last):
  File "<pyshell#267>", line 1, in <module>
    newfuncs[0]()
  File "<pyshell#261>", line 6, in ff
    res = f(*args, **key)
TypeError: f2() takes exactly 1 argument (0 given)

which is not.

I'll appreciate your help in pointing out the mistake in defining
cfuncs and how to fix it.
Thank you very much!




More information about the Python-list mailing list