Let's say we have a basic function:
def basic(arg):
print arg
We need to defer the evaluation of this function in another function. I am thinking about 2 possible ways:
Using lambdas:
def another(arg): return lambda: basic(arg)
Using functools.partial
from functools import partial def another(arg): return partial(basic, arg)
Which of these approaches is preferred and why? Is there another way of doing this?
I believe this mostly comes down to personal taste, although
functools.partial
is believed to be somewhat faster than an equivalentlambda
. I prefer to usefunctools.partial
in such situations as in my opinion it makes sense to indicate that we're dealing with a simple partial function application and not a full-blown closure.Lambdas don't store data which is not in its argument. This could lead to strange behaviors:
Expected output
Output
This happens because the lambda didn't store the
arg
value and it went through all the elements ofargs
, so nowarg
is always4
.The preferred way is to use
functools.partial
, where you are forced to store the arguments:Expected output
Output