recognizing empty iterators

Daniel Dittmar daniel.dittmar at sap.com
Tue Jul 22 12:09:17 EDT 2003


Michele Simionato wrote:
> I wanted to check the output of ifilter or imap; at the end I solved
> my problem in another way, nevertheless I am surprised there is no
> way to check for an empty iterator in current Python, it seems to be
> a quite legitimate question, isn't it?

It would make writing iterators more difficult because you'd have to know
that there is a first element before the first call to .next ().

It shouldn't be too difficult to write an iterator wrapper class that does
exactly what you want (not tested):

class IteratorWrapper:
    def __init__ (self, iterArg):
        iterArg = iter (iterArg)
        try:
            self.firstElement = iterArg.next ()
            self.isEmpty = false
            self.next = self.returnFirstElement
            self.baseIter = iterArg
        except StopIteration:
            self.isEmpty = true
            self.next = self.throwStopIteration

    def returnFirstElement (self):
        self.next = self.baseIter.next
        return self.firstElement

    def throwStopIteration (self):
        throw StopIteration

Daniel







More information about the Python-list mailing list