I want to wrap a function with the specified arguments, for example functools.partial , but it does not work properly:
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
output:
source expected: 0 callback from source: 2 source expected: 1 callback from source: 2 source expected: 2 callback from source: 2
But I want:
source expected: 0 callback from source: 0 source expected: 1 callback from source: 1 source expected: 2 callback from source: 2
I know this works if I use functools.partial , but I want to know the real problem in my code ... Does the lambda shell use the global variable source ?
source share