3 ms·
Python's solution is to throw a StopIteration exception when the iterator runs out. That works out ok as long as you don't manually throw it in weird places, bu
by duckerude 8y ago
Python's solution is to throw a StopIteration exception when the iterator runs out. That works out ok as long as you don't manually throw it in weird places, but a naive implementation could have high overhead because exceptions are expensive.
PHP's iterators have separate methods for advancing to the next element, checking if there's a current element, and getting the current element. That's cumbersome, and requires keeping extra state, but it's abstracted over so it doesn't typically matter. I think it mimics a bizarre old way of iterating through arrays.
There are multiple ways to signal the end. Javascript's is pretty clean.
- anonytrary 8y agoOof, I'd definitely take JavaScript's wrapper objects over an exception. Iteration complete isn't something that strikes me as an error, it's just the end of the finite list you're iterating over! Does the program expect the list to never end or something? Errors should be reserved for the unexpected. A list ending is very expected, unless you're dealing with an infinite generator.
- duckerude 8y agoPython uses exceptions more casually than many other languages. It follows EAFP. Exceptions don't have to be very exceptional. Doing it like that would be out of place in many languages with different sensibilities, but it fits ok in Python. It also helps that you rarely deal with StopIteration exceptions directly or even have to remember they're used under the hood.