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

Alan Kennedy alanmk at hotmail.com
Thu Nov 14 08:30:11 EST 2002


Alex Martelli wrote:

> 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()

Alex,

You have an amazing knack for finding elegant solutions!

I tried to come up with a one-liner that raised StopIteration, but
couldn't arrive at one.

If it was possible to raise an exception by instantiating an exception
class, then it would be even simpler, e.g.

def empty():
    yield StopIteration()

But that, of course, doesn't work.

Here is one last stab at it, which has the simplicity of my above
solution, at the expense of having to define a new class:

class emptyGenerator:

    def __init__(self):
        raise StopIteration()

def emptyGen():
    yield emptyGenerator()

Stuart Gathman said "How about a built-in null generator that can be
assigned to any desired name?"

Shouldn't be too hard to include such an "emptyGenerator" class
definition, for example in "site.py".

But I think I prefer the conciseness of Alex' solution.

regards,

-- 
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/mailto/alan



More information about the Python-list mailing list