I would like create a function, whose primary purpose is to do some task for each input in a big list, and append the output to a file after each iteration.
I also want the function to yield its output just in case I need to store the output in some variable.
So my solution is to make the function a generator as follows:
def print_squares(n):
"""Print the squares of all integers from 1 to n."""
num = 1
while num < n:
result = num**2
with open('results.txt', 'a') as f:
f.write(result)
yield result
num += 1
But I need to find a way to exhaust the generator, so that it can write all the outputs. What would be the best practice to do so?
Ideas that I've considered:
- Unpack the generator into a list, and discard the list:
-
N = 1000000000 [*print_squares(N)]
- This works, but it looks a bit ugly/"hacky" to me, because my original intent is not to create a list.
-
- Use a
for
loop which iterates through the generator:-
for result in print_squares(N): pass
- This works, but it uses two lines.
-
I wish python could pick up that there is no "sink" for the function output, and so exhaust it automatically, rather than just outputting a generator object. I.e: print_squares(N)
should exhaust the generator.
Alternatively, is there a function that can exhaust the generator in a readable way (maybe in itertools)? I.e. exhaust(print_squares(N))