breaking iteration of generator method
Tim Hochberg
tim.hochberg at ieee.org
Tue Nov 4 13:10:31 EST 2003
Brian wrote:
> Hello;
>
> What happens when a program breaks (think keyword 'break') its iteration
> of a generator? Is the old state in the generator preserved?
>
> Ex:
>
> # .gen() is generator method.
>
> for i in myObject.gen():
> if i == specialValue:
> break
>
> Do subsequent calls to .gen() start off with new locals?
It depends on how you do it. This::
for i in myObject.gen():
if i == specialValue:
break
# ...
for i in myObject.gen():
if i == otherSpecialValue:
break
# ...
Will start start with a new generator with new local each time since
each call to gen() creates a fresh generator. If you want to preserve
generator state between loop, what you do is::
generator = myObject.gen()
for i in generator:
if i == specialValue:
break
# ...
for i in generator:
if i == otherSpecialValue:
break
# ...
In this case, the same generator is used in each loop and the state is
preserved.
-tim
> Or, would
> the iteration begin after the yielded 'i' that caused the for-statement
> to exit?
>
>
> Many thanks,
>
> Brian.
More information about the Python-list
mailing list