question about generators

Bernhard Herzog bh at intevation.de
Thu Aug 15 13:56:23 EDT 2002


Andrew Koenig <ark at research.att.com> writes:

> Aha!  I just realized part of the origin of my puzzlement.
> 
> Yield actually does one of two very different things depending
> on context.  Consider:
> 
>         def f():
>                 yield 1
>                 yield 2
> 
> The "yield 1" statement does two things:
> 
>         1) It creates a generator object and returns that object to
>            the caller;

It doesn't. This happens when f is called. However, f doesn't really
start to execute until the generator's next() method is called:
>>> def f():
...     print 'a'
...     yield 1
...     print 'b'
...     yield 2
... 
>>> g = f()
>>> g.next()
a
1
>>> g.next()
b
2

>         2) When the caller calls the generator's "next" method,
>            it passes 1 back to the caller.
> 
> The "yield 2" statement does only one thing: It passes 2 back to the
> caller.
> 
> Let's call these two statements "type 1" and "type 2" yield
> statements.

All yields are of type 2

[...]
> These facts mean that yield statements break a form of abstraction
> that is commonplace in many other contexts: the ability to take a
> collection of statements and put them in a function.  For example:
> 
>         def f():
>                 <statement 1>
>                 <statement 2>
>                 <statement 3>
>                 <statement 4>
> 
> Under ordinary circumstances, I can rewrite this as
> 
>         def f():
>                 <statement 1>
>                 g()
>                 <statement 4>
> 
>         def g():
>                 <statement 2>
>                 <statement 3>
> 
> without changing the meaning of the program (provided that statement 2
> and statement 3 do not refer to local variables of f).

As you observe this doesn't for yield statements. In this regard yield
is just like return for which it wouldn't work either. Both yield and
return redirect the control flow back to the immediate caller, only with
return the caller is the caller of the function, with yield it's the
caller of the generator's next method.

   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                           http://www.mapit.de/



More information about the Python-list mailing list