Lambda or functools.partial for deferred function evaluation? [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-04 20:24:13

Lambdas don't store data which is not in its argument. This could lead to strange behaviors:

def lambdas(*args):
    for arg in args:
        yield lambda: str(arg)

one, two, three, four = lambdas(1, 2, 3, 4)
print one(), two(), three(), four()

Expected output

1 2 3 4

Output

4 4 4 4

This happens because the lambda didn't store the arg value and it went through all the elements of args, so now arg is always 4.

The preferred way is to use functools.partial, where you are forced to store the arguments:

from functools import partial

def partials(*args):
    for arg in args:
        yield partial(str, arg)

one, two, three, four = partials(1, 2, 3, 4)
print one(), two(), three(), four()

Expected output

1 2 3 4

Output

1 2 3 4
amgaera

I believe this mostly comes down to personal taste, although functools.partial is believed to be somewhat faster than an equivalent lambda. I prefer to use functools.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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!