(why) inconsistent yield/return syntax?

Steve Holden sholden at holdenweb.com
Mon Feb 10 17:07:46 EST 2003


"Gerrit Holl" <gerrit at nl.linux.org> wrote in message
news:mailman.1044910176.10436.python-list at python.org...
> Mark McEahern schreef op maandag 10 februari om 21:43:10 +0000:
> > [Gerrit Holl]
> > > > Read up on generators.  Google is your friend.
> > >
> > > I have.
> > > If if wouldn't have done that, it would be:
> > >
> > >   1 >>> def f(): yield
> > >   <stdin>:1: Warning: 'yield' will become a reserved keyword in the
future
> > >
> > > But it was:
> > >  46 >>> def f(): yield
> > >    File "<stdin>", line 1
> > >        def f(): yield
> >
> > That leaves me wondering what your question is then.
>
> An empty return is ok and return None, but an empty yield isn't.
> My question is why...
>

That's because a generator isn't a function. It's something that returns an
object designed to be repeatedly activated, typically by the iteration
protocol but possibly by calling its next() method, to return values. A
sequence of values. Each value is the argument of the next "yield" statement
executed in sequence by the reactivated generator body. So <sloppy
terminology>:

>>> def f(): yield 1
...
# we just defined a generator
>>> f
<function f at 0xa097590>
# see, this isn't really a lie: a generator is a function that returns an
iterator
>>> g = f()
# we bound an instance of the generator to g
>>> h = f()
# and another instance to h
>>> h
<generator object at 0xa0537c8>
# see ... ?
>>> h.next()
1
# The generator returns its next value
>>> h.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration
# and raises StopIteration when there aren't any more
>>> g.next()
1
# This shows that calling a generator gives a new iterator each time
>>>
</sloppy terminology>

Hope this helps. It doesn't make sense to have yield without an argument
because the iterator protocol requires an object be returned. You might
argue that None shoud be a default, but I think that would be asking for
trouble.

regards
--
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Register for PyCon now!            http://www.python.org/pycon/reg.html







More information about the Python-list mailing list