PEP 255: Simple Generators

Rainer Deyke root at rainerdeyke.com
Tue Jun 19 13:05:04 EDT 2001


"Neil Schemenauer" <nas at python.ca> wrote in message
news:mailman.992918729.26233.python-list at python.org...
> Rainer Deyke wrote:
> > In other words, whether a function is a generator or not is determined
at
> > run-time.  The following would work, right?
> >
> > def f(x):
> >   if x == 5:
> >     yield 5 # Look ma, I'm a generator.
> >     return
> >   else:
> >     return x # Or maybe not.
>
> No and no.  The above code would raise a syntax error when
> compiled.

In that case, there definitely should be a separate syntax for generators.
Consider:


def f():
  return
  yield 'Never reached.'


Is this function a generator?  Yes, but only if nobody removes the seemingly
redundant 'yield' statement.  Or consider a case like this:


def f(x):
  if x == 0:
    do_something()
  elif x == 1:
    do_something_else()
  # ...
  elif x == 99:
    yield 5


Here we have a very long function that doesn't fit on the screen all at
once.  A person looking at the upper part would think it a normal function,
and only somebody who sees the bottom part of the function knows it's a
generator.  If the last case becomes redundant for some reason and is
removed, the semantics of the entire function change.


--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list