yield

Gerrit Holl gerrit at nl.linux.org
Sat Jan 17 14:46:59 EST 2004


Hi km,

km wrote:
> Hi gerrit,
> 
> i ran the snippet but i am sorry, i couldnt get what u were saying.
> kindly enlighten,

If a function reads a 'return' statement, it is finished. It returns the
value, and never reaches the part after the 'return' statement. If a
generator reaches a 'yield' statement, it returns the result of the
expression behind the 'yield' statement. When you call a function which
returns values not with 'return' but with 'yield', it returns a
generator. When you call the 'next' method of the generator, the body is
executed, until it reaches a 'yield' statement. When you call the body
again, it is executed again, until it reaches a 'yield' statement again,
etc, until it does not reach any 'yield' statement again, and then it
raises StopIteration. This way, you can for example implement something
which returns the Fibonacci series:

>>> def f():
...    a, b = 0, 1
...    while True:
...        a, b = b, a+b
...        yield a

You can now define a generator by calling f():

>>> g = f()
>>> g.next()
1
>>> g.next()
1
>>> g.next()
2
>>> g.next()
3
>>> g.next()
5
>>> g.next()
8
>>> g.next()
13

...etc. It would be difficult to do this with a function. You could use
a global variable, or create a class with some methods, but the first
way is ugly and the second way is really a different way to create a
generator (I think it's called an 'explicit generator' whereas a
function with a yield statement is an 'implicit generator' - I'm not
sure, maybe someone can clarify?). An 'iterator' is anything you can put
'for' in front of. You could do 'for i in g:' here, but it would be an
endless loop, so we'll break out of it:

>>> for i in g:
...    print i,
...    if i > 100:
...        break
21 34 55 89 144

It started at 21 because that's where we stopped with our last .next()
method.

Generators are documented at different places in the documentation. The
tutorial: http://www.python.org/doc/current/tut/node11.html
What's new: http://www.python.org/doc/2.3.3/whatsnew/section-generators.html
PEP 255: http://www.python.org/peps/pep-0255.html

There is also information in the Language Reference, but this is
probably not very useful.

yours,
Gerrit.

-- 
40. He may sell field, garden, and house to a merchant (royal agents)
or to any other public official, the buyer holding field, house, and
garden for its usufruct.
          -- 1780 BC, Hammurabi, Code of Law
-- 
PrePEP: Builtin path type
    http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html
Asperger's Syndrome - a personal approach:
	http://people.nl.linux.org/~gerrit/english/




More information about the Python-list mailing list