[Tutor] generator object

Peter Otten __peter__ at web.de
Wed Aug 31 05:09:14 EDT 2016


monikajg at netzero.net wrote:

> So generator function returns generator object according to Aaron Maxwell.

It's always nice to give a link or a quote.

> But does this mean that each time yields "returns" it is a generator
> object? So if there are 5 yield "returns" there are 5 generator objects?
> Or is there always only one generator object returned by the generator
> functions? Can somebody please explain? Thank you Monika ----------

By "generator function" he probably means something like

>>> def f():
...     yield "foo"
...     yield "bar"
... 

According to Python that's a function:

>>> f
<function f at 0x7fe3e137e488>

Let's invoke it to see what it returns:

>>> f()
<generator object f at 0x7fe3e130f2d0>
>>> f()
<generator object f at 0x7fe3e130f360>
>>> f()
<generator object f at 0x7fe3e130f318>

So these are indeed "generator objects", they are distinct (you get a new 
one on every invocation of f()) as you can verify by looking at their IDs 
(the hexadecimal numbers in the representation).

However, the number of yield-s does not come into play yet. If there are any 
in the function body, it's not a "normal function", it's a "generator 
function". The yield-s show their effect when you iterate over the generator

>>> for item in f(): print(item)
... 
foo
bar

or apply next():

>>> g = f()
>>> next(g)
'foo'
>>> next(g)
'bar'
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

The number of values you can get from a generator is not determined by the 
number of yield-s as one yield-expression may be executed more than once. 
The following example can run "forever":

>>> def step(start, delta):
...     value = start
...     while True:
...         yield value
...         value += delta
... 
>>> two = step(0, 2)
>>> three = step(42, 3)
>>> 
>>> next(two)
0
>>> next(two)
2
>>> next(two)
4
>>> next(three)
42
>>> next(three)
45
>>> for a, b in zip(two, three):
...     print(a, b)
...     if a > 10: break
... 
6 48
8 51
10 54
12 57






More information about the Tutor mailing list