#TIL Python's iter function has a two argument form. It's use allows you to convert a function that successively returns values until a certain sentinel value is returned into a Python iterator.
https://docs.python.org/3/library/functions.html?highlight=iter#iter
A good example would be file.readline, which returns the empty string ('') when the end of a file is reached.
for line in iter(f.readline, ''):
print(line)
(Of course, since file-objects are already iterable, you can just directly iterate over lines that way, but this technique can be applied to any sentinel-style API)
Also be sure to check out these notes from Raymond Hettinger's "Transforming Code into Beautiful, Idiomatic Python" talk from pycon US 2013:
https://gist.github.com/JeffPaine/6213790
#Python #iterator
https://docs.python.org/3/library/functions.html?highlight=iter#iter
A good example would be file.readline, which returns the empty string ('') when the end of a file is reached.
for line in iter(f.readline, ''):
print(line)
(Of course, since file-objects are already iterable, you can just directly iterate over lines that way, but this technique can be applied to any sentinel-style API)
Also be sure to check out these notes from Raymond Hettinger's "Transforming Code into Beautiful, Idiomatic Python" talk from pycon US 2013:
https://gist.github.com/JeffPaine/6213790
#Python #iterator