I want to wrap a function with specified arguments, something like functools.partial, but it doesn't work as expected:
source_codes = (0, 1, 2)
def callback(source, *args):
print 'callback from source: ', source
funcs = []
for source in source_codes:
funcs.append(lambda *args: callback(source, *args))
for i, func in enumerate(funcs):
print 'source expected: ', i
func()
print
the output:
source expected: 0
callback from source: 2
source expected: 1
callback from source: 2
source expected: 2
callback from source: 2
But...What I want is:
source expected: 0
callback from source: 0
source expected: 1
callback from source: 1
source expected: 2
callback from source: 2
I know it works if I use functools.partial
, but I want to know the real problem in my code... Does the lambda wrapper use a global variable source
?