The second argument of the iter
function is useful for looping over objects that don't define themselves as iterable, such as binary files:
response = b''
for block in iter(partial(f.read, 256), b''):
response += block
However in Python 3.8 we now have the “the walrus operator”, which in the What's new in Python 3.8 article is mentioned as way to solve the exact problem above:
# Loop over fixed length blocks
while (block := f.read(256)) != '':
process(block)
I wonder if the later is now considered "the right approach"? And if so, if there is ever any need for the second argument of iter
, since any code on the form
for x in iter(f, y):
g(x)
might as well now be written:
while (x := f()) != y:
g(x)
I guess there might still be cases where we don't want to immediately loop the iterable, such as b''.join(iter(partial(f.read, 256), b''))
or some code (though it quickly gets pretty hairy).
Also a loop like for i, x in enumerate(iter(f, y)):
might be hard to translate to the new syntax(?)
The PEP for walrus only mentions 2-arg iter
in the example while h(x := f()): g(x)
, which it says can't trivially be translated to iter
.
Python usually have pretty precise guidelines on these sorts of things, but I haven't been able to find any for this particular issue. Can you help me?