My (late) beef with Simple Generator syntax (PEP 255)

Alex Martelli aleax at aleax.it
Thu Nov 14 06:28:32 EST 2002


Terry Reedy wrote:

> 
> "Cameron Horn" <camhorn at mac.com> wrote in message
> news:mailman.1037240419.5238.python-list at python.org...
>>>> If I want to write an empty generator, I write this(?):
>>>> def foo():
>>>>    return
>>>>    yield "never"
> 
> <my previous comment clipped>
> 
> I prefer (see below for why)
> 
> def null():
>   raise StopIteration
>   yield 1/0

I think that if I ever had to write an empty generator I'd prefer a 
single-statement version, such as, for example:

def empty():
    yield iter([]).next()

The .next call to the iterator object, constructed on the fly on any
empty iterable, raises StopIteration, and empty()'s yield statement
just cleanly propagates it.  More generally, the preference is for
any statement of the form:

    yield <any expression that raises StopIteration>

calling .next() on an empty iterator seems the most natural way to
get "an expression that raises StopIteration", but there may be
better ones -- or more natural ways to get an empty iterator than
calling iter([]) -- though none readily comes to mind offhand.


Alex




More information about the Python-list mailing list