Testing for empty iterators?

Larry Bates lbates at swamisoft.com
Tue Jul 6 18:29:45 CEST 2004

Normally I add a __len__ method to my class
that contains an iterator if I need to keep
track of length/empty status.  Basically it
is something like:

class getListOfThing:
    def __init__(self):
        # Code to build ListOfThings can be inserted here
        # or in some other method.

    def __iter__(self):
        return self

    def next(self):
        # Try to get the next Thing
        try: Thing=self.ListOfThings[self.next_index]
        except IndexError:
            raise StopIteration
        # Increment the index pointer for the next call
        return Thing

    def __len__(self):
        return len(self.ListOfThings)
        # Where ListOfThings is an attribute
        # (list) that is defined in __init__
        # and appended to in some way.

if __name__=="__main__":

print "Length of ListOfThings=",len(T)
for Thing in T:
    # do something with Thing

But most of the time the fact that the iterator
doesn't return enything, so the loop is skipped
automatically is sufficient.  I think you can do
this same thing with a yield, but this method works
and I continue to use it a lot.

Larry Bates
Syscon, Inc.

"Roy Smith" <roy at panix.com> wrote in message
news:roy-0D409A.14060003072004 at reader2.panix.com...
> In the old days, if I wanted to return a sequence of items, I'd return a
> list, and loop over it like this:
> for thing in getListOfThings ():
>    do something
> With iterators, I'm doing:
> for thing in getThingIterator ():
>    do something.
> Now I need to test to see if the iterator is empty.  Actually, it's a
> unit test where I want to assert that it is empty. In the old days, I
> would have done:
> assertEquals (getListOfThings (), [])
> but I don't see any clean way to do this with an iterator.  The best I
> can come up with is something like:
> flag = False
> for thing in getThingIterator ():
>    flag = True
>    break
> assertEquals (flag, False)
> Is that really the only way to do it?

More information about the Python-list mailing list