Has Next in Python Iterators
steve at REMOVE-THIS-cybersource.com.au
Thu Oct 21 14:26:50 CEST 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
x = random.random()
while x < 0.5:
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:
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.
More information about the Python-list