2011/6/29 Floris van Manen <v...@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 || r...@hooft.net || http://hooft.net/rob _______________________________________________ Python-nl mailing list Python-nl@python.org http://mail.python.org/mailman/listinfo/python-nl