Generating a List of Lambda


def cm():
 return [lambda x:i*x for i in range(3)]

for m in cm():
 print(m(1),end='')

Above is Python 3 sample. Which won't work since the lambdas are bound with i . But i is in rotation. So the Lambdas are created with binding to a var, when the Lambdas are evaluated, the var keeps the last value as "2" in current example. This is common Late Binding behavior as usual functions.

Solution 1: Use iterator rather than list

def cm():
 return (lambda x:i*x for i in range(3))

for m in cm():
 print(m(1))

Solution 2: Creating a Closure to Evaluate Arguments Immediately

Another way to mitigate the Late Binding is to create a Closure to immediately evaluate the parameters with a temporary variable.

def clip():
    return [lambda x, i=i: i*x  for i in range(3)]

However, the closure hacking is still a debating way to take more assumptions on language or interpreter implementation.

References

http://python-guide-pt-br.readthedocs.io/en/latest/writing/gotchas/#late-binding-closures

results matching ""

    No results matching ""