[python-nl] lambda rewrite question

Sylvain Viollon sylvain at infrae.com
Wed Jun 29 16:30:44 CEST 2011


On Wed, 29 Jun 2011 16:01:38 +0200
Floris van Manen <vm at klankschap.nl> wrote:

  Hello,

> this doesn't
> if i call the function it will return a (random?) identical value for
> all stored lambda functions.
> 
> def rewrite( d ):
>     for key in d:
>         for k in d[key]['next']:
>             c = float(d[key]['next'][k]['prob'])
>             d[key]['next'][k]['prob'] = lambda : c
>     return d
> 
> 
> There is most likely a reason to it.
> Can someone explain me what that reason is ?
> 

  c refer to only one variable, which scope is the function rewrite.

  lambda here create a closure that return the value of this unique
  variable, that will have as value the one computed in the last
  iteration of your loop (that's not random).

  Regards,

  Sylvain,

-- 
Sylvain Viollon -- Infrae
t +31 10 243 7051 -- http://infrae.com
Hoevestraat 10 3033GC Rotterdam -- The Netherlands


More information about the Python-nl mailing list