4 ms·
Why not something like this: def f_iter(many, args): while True: m = f(many, args) if m: yield m else:
by ygrechuk 7y ago
Why not something like this:
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.
- repsilat 7y agoAnd less reasonably, something similar for regular expressions: for m in filter([re.match(...)], bool): ... ;-)
- mlevental 7y agoso i should write a whole other function that iterates over a list instead of being happy that := exists?
- throwaway744678 7y agoYes! No pain, no gain!
- ciupicri 7y agoInstead of raising StopIteration you could also just return from the function. You could also make it a bit shorter if you swap the if branches. def f_iter(many, args): while True: m = f(many, args) if not m: return yield m
- zb 7y agoInstead of raising StopIteration you have to return from the function, otherwise you'll just get a RuntimeError starting with Python 3.7.
- ciupicri 7y agoYou're right. The [changelog] for Python 3.7 states: > [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 https://docs.python.org/3.7/whatsnew/changelog.html#id115 [bpo-32670]: https://bugs.python.org/issue32670 https://bugs.python.org/issue32670 [PEP 479]: https://www.python.org/dev/peps/pep-0479/ https://www.python.org/dev/peps/pep-0479/
- bvrmn 7y agoPython has built-in facilities for that, there is no need to write wrapper by yourself. from functools import partial with open('mydata.db', 'rb') as f: for block in iter(partial(f.read, 64), b''): process_block(block)