Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #75337

What happens when you 'break' a generator?

From "Frank Millman" <frank@chagford.com>
Subject What happens when you 'break' a generator?
Date 2014-07-29 09:18 +0200
Newsgroups comp.lang.python
Message-ID <mailman.12403.1406618335.18130.python-list@python.org> (permalink)

Show all headers | View raw


Hi all

Python 3.4.1

Here is a simple generator -

def test():
    print('start')
    for i in range(5):
        yield i
    print('done')

x = test()
for j in x:
    print(j)

As expected, the output is -

start
0
1
2
3
4
done

Here I break the loop -

x = test()
for j in x:
    print(j)
    if j == 2:
        break

Now the output is -

start
0
1
2

'done' does not appear, so the generator does not actually terminate. What 
happens to it?

My guess is that normal scoping rules apply. Using my example, the generator 
is referenced by 'x', so when 'x' goes out of scope, the generator is 
garbage collected, even though it never completed.

Is this correct?

Frank Millman


Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

What happens when you 'break' a generator? "Frank Millman" <frank@chagford.com> - 2014-07-29 09:18 +0200

csiph-web