recognizing empty iterators
Chris Perkins
chrisperkins37 at hotmail.com
Mon Jul 21 16:20:43 EDT 2003
mis6 at pitt.edu (Michele Simionato) wrote in message
> I realized that I don't know a satisfactory way to check if an
> iterator is empty. In other words I am looking for an
> "isempty" function to use in "if" statements such as
>
> if isempty(iterator):
> do_something()
>
> without side effects.
>
In general, it is impossible to test whether an iterator is exhausted.
For example, how would you test the following:
import random
def am_i_empty():
while random.choice((True,False)):
yield 42
return
So you have to call "next" - there's no way around it. You just need a
wrapper to cache the value:
class checkable_iter:
def __init__(self,it):
self.it = iter(it)
self.cached = []
def isempty(self):
if self.cached:
return False
try:
self.cached.append(self.it.next())
return False
except StopIteration:
return True
def next(self):
if self.cached:
return self.cached.pop()
return self.it.next()
>>> it = checkable_iter(am_i_empty())
>>> it.isempty()
False
>>> it.next()
42
>>> it.isempty()
True
>>> it.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
Chris
More information about the Python-list
mailing list