Edit: 1 line, not 2 (excluding the "do stuff")
def f_iter(many, args):
while True:
m = f(many, args)
if m:
yield m
else:
raise StopIteration
...
for m in f_iter(many, args):
# do stuff with m
This way you’re isolating all the initialization logic, error handling, etc. And you can focus on your domain logic in your client code. from functools import partial
with open('mydata.db', 'rb') as f:
for block in iter(partial(f.read, 64), b''):
process_block(block) def f_iter(many, args):
while True:
m = f(many, args)
if not m:
return
yield m> [bpo-32670]: Enforce [PEP 479] for all code. This means that manually raising a StopIteration exception from a generator is prohibited for all code, regardless of whether ‘from __future__ import generator_stop’ was used or not.
[changelog]: https://docs.python.org/3.7/whatsnew/changelog.html#id115
[bpo-32670]: https://bugs.python.org/issue32670
[PEP 479]: https://www.python.org/dev/peps/pep-0479/
for m in filter([re.match(...)], bool):
...
;-)Also if it comes to pure form I would have preferred `while (evaluate) as x:` out of establishing a parallel with existing syntax, but that's not very important.
In that sense, while loops over expressions always require knowledge of the expression to understand the semantic. On the other hand, something like:
while True:
with x as y:
print(y)
would not require understanding of x to understand the intent. Therefore it is not semantically equivalent to: while x as y:
print(y)
Note that in both cases, `:=` is strictly equivalent to `as` as it is defined for `with`. That is a matter of personal preference.