generator slides review
Terry Reedy
tjreedy at udel.edu
Mon Feb 3 19:55:03 EST 2014
On 2/3/2014 5:22 PM, andrea crotti wrote:
> That's already better, another thing which I just thought about could
> be this (which actually happened a few times):
>
> def original_gen():
> count = 0
> while count < 10:
> yield count
> count += 1
>
>
> def consumer():
> gen = original_gen()
> # lis = list(gen)
> for n in gen:
> print(n * 2)
>
> if I uncomment the line with "lis = list(gen)"
> it won't print anything anymore, because we have to make sure we only
> loop over ONCE.
> That maybe is a better example of possible drawback? (well maybe not a
> drawback but a potential common mistake)
A couple of days ago I made a similar error. Stdlib code
a = list(f(iterable1))
return g(a) # g just need an iterable
The return value is buggy. Insert for i in a: print(i) to debug. Notice
that g does not need a concrete list. Delete list wrapper. Return value
goes away. Because I did other things between the last two steps, I did
not immediately make the connection and was initially puzzled. Deleting
debug code made things work again. Using itertools.tee would have done
the same.
--
Terry Jan Reedy
More information about the Python-list
mailing list