(why) inconsistent yield/return syntax?

Alex Martelli aleax at aleax.it
Tue Feb 11 05:08:01 EST 2003


Andrew Koenig wrote:

> Mark> "How do I define a zero-length iterator?"
> 
> Mark> def whynot():
> Mark>     if True:
> Mark>         raise StopIteration
> Mark>     yield None
> 
> I think I like the following version better:
> 
>         def whynot():
>                 return
>                 yield None
> 
> because it doesn't explicitly depend on StopIteration.

I think the most concise form (in some sense) of a
zero-length _generator_ may be:

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

this doesn't explicitly depend on StopIteration either:
it implicitly and subtly depends on an empty iterator
raising it when its .next method is called.  It is
"concise" in that its body's a single, simple statement,
and thus the whole generator can be on a single line.

However, I think this is too tricky and cute.


If one's happy with any empty _iterator_, though:

def zeroleniter(): return iter([])

is clearly simpler and even more concise.  I see
no reason to use any other form.


Alex





More information about the Python-list mailing list