breaking iteration of generator method

Peter Otten __peter__ at web.de
Tue Nov 4 19:10:51 CET 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? Or, would
> the iteration begin after the yielded 'i' that caused the for-statement
> to exit?
> 
> 
> Many thanks,
> 
> Brian.

Running the following little demo should answer you questions.
The Mark class is used only to show when the generator dies, it relies on
CPython's garbage collection algorithm.

class Mark(object):
    def __init__(self):
        print "created"
    def __del__(self):
        print "gone"

def gen():
    mark = Mark()
    for i in range(10):
        yield i


for i in gen():
    print i,
    if i == 5:
        print "breaking"
        break

g = gen()
for i in g:
    print i,
    if i == 5:
        print "breaking"
        break

while True:
    print g.next()

Peter




More information about the Python-list mailing list