A gotcha: Python pain point?
Diez B. Roggisch
deets at nospam.web.de
Tue Jun 12 10:51:57 CEST 2007
James Stroud wrote:
> Beorn wrote:
>> Consider this example:
>> >>> def funcs(x):
>> ... for i in range(5):
>> ... def g(): return x + i
>> ... yield g
>> I would expect the value of x used in g to be that at the function
>> declaration time, as if you've pass g a (x=x) argument, especially
>> after reading this post: http://lua-users.org/wiki/LuaScopingDiscussion
>> >>> [ fun() for fun in list(funcs(1)) ]
>> [5, 5, 5, 5, 5]
>> >>> [ fun() for fun in funcs(1) ]
>> [1, 2, 3, 4, 5]
>> This came up while discussing Python pain points at
>> I can see how it works now, but I haven't found an easy-to-read
>> documentation on this.
>> I guess it's debatable if perhaps every i used in the loop shouldn't
>> be a different i. It had me fooled, anyways.
> If this isn't classified as a bug, then someone has some serious
> explaining to do. Why would it be desirable for a generator to behave
> differently in two different contexts. Should I import this to see how
> many principles this behavior violates?
It's no bug. The generator behaves the same way in both cases. What is
different is the calling time of the function.
Certainly a surprising outcome. But no bug.
More information about the Python-list