varargs in lambda functions in Python

喜夏-厌秋 提交于 2019-12-02 22:17:32

There is no problem using varargs in lambda functions. The issue here is different:

The problem is that the the lambda refrences the loop variable v. But by the time the lambda is called, the value of v has changed and the lambda calls the wrong function. This is always something to watch out for when you define a lambda in a loop.

You can fix this by creating an additional function which will hold the value of v in a closure:

def create_not_function(v):
    return lambda s, *args, **kw:  not v(s, *args, **kw)

for (k, v) in _dict.items():
    if hasattr(v, '__call__'):
        extended_dict["not_" + k] = create_not_function(v)

Yes.

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