Skip to the content.

G+: #TIL Python's iter function has a two argument …

David Coles
#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

2. Built-in Functions — Python 3.6.0 documentation


(+1's) 4
Matt Giuca
That's handy, and also TIL. But a pretty awful design to have a function where, by its own admission, "the first argument is interpreted very differently depending on the presence of the second argument."

Probably should just be a separately named function.

David Coles
The Python built-ins are particularly bad for this. I know I've run into a few other functions that could only be implemented in C (e.g. see the documented signatures of min, max, dict). Kind of frustrating since it means these functions are completely invisible to introspection functions and extremely hard to wrap properly.