So, I was watching Raymond Hettinger's talk Transforming Code into Beautiful, Idiomatic Python and he brings up this form of iter
which I was never aware of. His example is the following:
Instead of:
blocks = []
while True:
block = f.read(32)
if block == '':
break
blocks.append(block)
Use:
blocks = []
read_block = partial(f.read, 32)
for block in iter(read_block, ''):
blocks.append(block)
After checking the documentation of iter
, I found a similar example:
with open('mydata.txt') as fp:
for line in iter(fp.readline, ''):
process_line(line)
This looks pretty useful to me, but I was wondering if of you Pythonistas know of any examples of this construct that doesn't involve I/O-read loops? Perhaps in the Standard Library?
I can think of very contrived examples, like the following:
>>> def f():
... f.count += 1
... return f.count
...
>>> f.count = 0
>>> list(iter(f,20))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>>
But obviously this is not any more useful that the built-in iterables. Also, it seems like code smell to me when you are assigning state to a function. At that point, I'd likely should be working with a class, but if I'm going to write a class, I might as well implement the iterator protocol for whatever I want to accomplish.
See Question&Answers more detail:
os