Question about lambda and variable bindings

poof65 poof65 at gmail.com
Sun Mar 2 04:11:24 CET 2008


An idea, i don't know if it will work in your case.

for x in xrange(10):
  funcs.append(lambda p,z=x: testfunc(z+2,p))

On Sun, Mar 2, 2008 at 3:50 AM, Michael Torrie <torriem at gmail.com> wrote:
> I need to use a lambda expression to bind some extra contextual data
>  (should be constant after it's computed) to a call to a function.  I had
>  originally thought I could use something like this demo (but useless) code:
>
>  funcs=[]
>
>  def testfunc(a,b):
>     print "%d, %d" % (a,b)
>
>  for x in xrange(10):
>     funcs.append(lambda p: testfunc(x+2,p))
>
>
>  Now what I'd like is to call, for example, funcs[0](4) and it should
>  print out "2,4".  In other words I'd like the value of x+2 be encoded
>  into the lambda somehow, for funcs[x].  However the disassembly shows
>  this, which is reasonable, but not what I need:
>
>  >>> dis.dis(funcs[0])
>   2           0 LOAD_GLOBAL              0 (testfunc)
>               3 LOAD_GLOBAL              1 (x)
>               6 LOAD_CONST               0 (2)
>               9 BINARY_ADD
>              10 LOAD_FAST                0 (p)
>              13 CALL_FUNCTION            2
>              16 RETURN_VALUE
>
>  The LOAD_GLOBAL 1 (x) line is definitely a problem.  For one it refers
>  to a variable that won't be in scope, should this lambda be called from
>  some stack frame not descended from the one where I defined it.
>
>  So how can I create a lambda expression that calculates a constant based
>  on an expression, rather than referring to the object itself?  Can it be
>  done?
>
>  Michael
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list