Python lambda绑定到本地值 [英] Python lambda's binding to local values

查看:114
本文介绍了Python lambda绑定到本地值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码吐出了 1 两次,我希望看到 0 ,然后 1

The following code spits out 1 twice, I expect to see 0 and then 1

def pv(v) :
  print v


def test() :
  value = []
  value.append(0)
  value.append(1)
  x=[]
  for v in value :
    x.append(lambda : pv(v))
  return x

x = test()
for xx in x:
  xx()



我希望python lambdas绑定到一个局部变量指向的引用现场。但是似乎不是这样的。我已经在一个大型系统中解决了这个问题,其中lambda正在做现代C ++的等价的绑定('boost :: bind'例如),在这种情况下,你将绑定到一个智能ptr或副本构造一个副本的lambda。

I expected python lambdas to bind to the reference a local variable is pointing to, behind the scene. However that does not seem to be the case. I have enountered this problem in a large system where the lambda is doing modern C++'s equavalent of a bind ('boost::bind' for example) where in such case you would bind to a smart ptr or copy contstruct a copy for the lambda.

那么,如何将局部变量绑定到lambda函数,并在使用时保留正确的引用?我相当gobsmacked的行为,因为我不会指望从一个垃圾回收器的语言。

So, how do I bind a local variable to a lambda function and have it retain the correct reference when used? I'm quite gobsmacked with the behaviour since I would not expect this from a language with a garbage collector.

问题代码如下(l3_e是导致问题的变量):

The code in question looks as follows (l3_e is the variable which is causing the problem) :

 for category in cat :
      for l2 in cat[category].entries :
        for l3 in cat[category].entries[l2].entry["sub_entries"] :
          l3_e = cat[category].entries[l2].entry["sub_entries"][l3]
          url = "http://forums.heroesofnewerth.com/" + l3_e.entry["url"]
          self.l4_processing_status[l3_e] = 0
          l3_discovery_requests.append( Request(
            url, callback = lambda response : self.parse_l4(response,l3_e)))
          print l3_e.entry["url"]
    return l3_discovery_requests


推荐答案

更改 x.append(lambda:pv(v)) x.append(lambda v = v:pv(v))

Change x.append(lambda : pv(v)) to x.append(lambda v=v: pv(v)).

你期望python lambdas绑定到局部变量指向的引用,在场景后面,但这不是如何Python工作。 Python在调用函数时查找变量名称,而不是在创建时。使用默认参数是有效的,因为默认参数在函数创建时被计算,而不是在被调用时。

You expect "python lambdas to bind to the reference a local variable is pointing to, behind the scene", but that is not how Python works. Python looks up the variable name at the time the function is called, not when it is created. Using a default argument works because default arguments are evaluated when the function is created, not when it is called.

这不是lambdas的特别之处。考虑:

This is not something special about lambdas. Consider:

x = "before foo defined"
def foo():
    print x
x = "after foo was defined"
foo()

定义foo之后的

prints

after foo was defined

这篇关于Python lambda绑定到本地值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆