Python lambda's binding to local values

后端 未结 2 468
你的背包
你的背包 2020-11-22 16:48

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

def pv(v) :
  print v

x = []
for v in range(2)         


        
2条回答
  •  旧时难觅i
    2020-11-22 17:07

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

    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.

    This is not something special about lambdas. Consider:

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

    prints

    after foo was defined
    

提交回复
热议问题