How can I define anonymous functions in python, where the bahaviour should depend on the value of a local variable at definiton-time, and also accept arguments
Example:
def callback(val1, val2):
print "{0} {1}".format(val1, val2)
i = 0
f0 = lambda x: callback(i, x)
i = 1
f1 = lambda x: callback(i, x)
f0(8) # prints "1, 8: but I'd like "0, 8" (value of 'i' when f0 was defined)
f1(8) # prints "1, 8"
Is something like this possible without wrapping my callback in its own a class?
Closures in python using functools.partial
partialis like a lambda but wraps the value at that moment into the arg. Not evaluating it when its called.Wrapping only some of the args
Yes partial will allow you to wrap any number of the arguments, and the remaining args and kwargs can then be passed to the resulting partial object so that it acts like it was calling the original wrapped function…
Essentially you have wrapped
callback(val1, val2)intocallback(val2)withval1being included as a closure already.Example of similar effect using lambda
In case you really want to see how to do this with a lambda closure, you can see why it gets ugly and partial is preferred…
You have to wrap the scope variable into an outer function scope, and then reference that scope in the inner lambda function. Yuk.
Tracebacks from exceptions: partial vs lambda vs nested functions
With the influx of other answers, I thought I would outline one more reason to use partial as opposed to lambda, or a inner/outer function closure. Keep in mind I mean a function closure. functools.partial fixes the traceback you will get when your wrapped function raises an exception…
Consider this version that will raise a division by zero:
Normal outter/inner closure
lambda closure
And now for functools.partial