empty lists vs empty generators

Roy Smith roy at panix.com
Mon May 2 20:17:20 EDT 2005


In article <509534af.0505021514.5e49aa2 at posting.google.com>,
 brian at mirror.org (Brian Roberts) wrote:

> I'm using using generators and iterators more and more intead of
> passing lists around, and prefer them.  However, I'm not clear on the
> best way to detect an empty generator (one that will return no items)
> when some sort of special case handling is required.

The best I can come up with is to depend on the fact that

for item in foo:
   pass

only defines item if foo yields any items.  Assuming item is not defined 
before you execute the for loop, you can check to see if it's defined after 
the loop, and use that to tell if foo was an empty list or generator.  
Here's a demo.  Unfortunately, I'm not sure if it's really any cleaner than 
your way (but at least it doesn't add any extraneous variables)


# Creates an iterator which yields n items.
class gen:
    def __init__(self, n):
        self.n = n

    def __iter__(self):
        for i in range(self.n):
            yield None

def checkEmpty(genOrList):
    for item in genOrList:
        pass

    try:
        item
        print "%s had items" % genOrList
    except NameError:
        print "%s was empty" % genOrList

checkEmpty(gen(0))
checkEmpty(gen(1))
checkEmpty([])
checkEmpty([1])

--------------

Roy-Smiths-Computer:play$ ./gen.py
<__main__.gen instance at 0x36c620> was empty
<__main__.gen instance at 0x36c620> had items
[] was empty
[1] had items



More information about the Python-list mailing list