Has Next in Python Iterators

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Oct 21 08:26:50 EDT 2010


On Thu, 21 Oct 2010 09:36:41 -0200, Felipe Bastos Nunes wrote:

> Looking in the documentation, only the StopIteration raises. I'd like a
> hasNext() too. I'll see if it is easy to implement,


Iterators can be unpredictable. In general, you can't tell whether an 
iterator is finished or not until you actually try it. Consider the 
following example:

def rand():
    x = random.random()
    while x < 0.5:
        yield x

it = rand()


What should it.hasNext() return?

I know what you're thinking: "it's easy to cache the next result, and 
return it on the next call". But iterators can also be dependent on the 
time that they are called, like in this example:

def evening_time():
    while 1:
        yield time.strftime("%H:%m")  # e.g. "23:20"


it = time_of_day()  # it's 23:59
if it.hasNext(): # Returns True
    time.sleep(180)  # Do some other processing for three minutes
    print it.next()  # time is now 00:02, but iterator says it's 23:59



Of course, caching the result of an iterator can work for *some* 
iterators. But it's not a general solution suitable for all iterators. 
There is no general solution.



-- 
Steven



More information about the Python-list mailing list