[python-nl] lambda rewrite question

Rob Hooft rob at hooft.net
Wed Jun 29 18:18:11 CEST 2011


2011/6/29 Floris van Manen <vm at klankschap.nl>:
> For those of you who know everything about the basic python syntax & semantics ...
> I get stuck in a simple context issue (i think)
>
>
> this version works, it return the stored float value
>
> 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'] = c
>    return d
>
>
>
> 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 ?

The latter function will set all values to the same function,
returning the value of "c". So, they will all report the last value of
"c". Your lambda is almost the same as defining the function
elsewhere:

 def rewrite( d ):
    def utility():
          return c
    for key in d:
        for k in d[key]['next']:
            c = float(d[key]['next'][k]['prob'])
            d[key]['next'][k]['prob'] = utility
    return d

Rob

-- 
Rob W. W. Hooft || rob at hooft.net || http://hooft.net/rob


More information about the Python-nl mailing list