python - How to handle an exhausted iterator? -
while searching python documentation found equivalent python implementation of pythons build-in zip()
function.
instead of catching stopiteration
exception signals there no further items produced iterator the author(s) use if
statement check if returned default value form next()
equals object()
("sentinel
") , stop generator:
def zip(*iterables): # zip('abcd', 'xy') --> ax sentinel = object() iterators = [iter(it) in iterables] while iterators: result = [] in iterators: elem = next(it, sentinel) if elem sentinel: return result.append(elem) yield tuple(result)
i wonder if there any difference between exception catching or if
statement used python docs?
or better, @hiro protagonist pointed out:
what's wrong using try
statement considering eafp (easier ask forgiveness permission) in python?
def zip(*iterables): # zip('abcd', 'xy') --> ax iterators = [iter(it) in iterables] while iterators: result = [] in iterators: try: elem = next(it) except stopiteration: return result.append(elem) yield tuple(result)
also stoyan dekov mentioned "a try/except block extremely efficient if no exceptions raised. catching exception expensive." (see docs more information)
but exception occur once, namely iterator exhausted. so exception handling better solution in case?
you mean opposed this?
def zip2(*iterables): # zip('abcd', 'xy') --> ax iterators = [iter(it) in iterables] while iterators: result = [] in iterators: try: elem = next(it) except stopiteration: return result.append(elem) yield tuple(result)
interesting question... i'd have preferred alternative version - considering eafp (easier ask forgiveness permission.)
even if try/except slower if statement; happens once - first iterator exhausted.
it may worth noting not actual implementaion in python; implementation equivalent real implementation.
update according comments:
note pep 479 suggests return
generator , not raise stopiteration
.
Comments
Post a Comment