[Python-ideas] Deterministic iterator cleanup
Nick Coghlan
ncoghlan at gmail.com
Wed Oct 26 11:21:03 EDT 2016
On 26 October 2016 at 01:59, Yury Selivanov <yselivanov.ml at gmail.com> wrote:
> But how would it help with a partial iteration over generators
> with a "with" statement inside?
>
> def it():
> with open(file) as f:
> for line in f:
> yield line
>
> Nathaniel proposal addresses this by fixing "for" statements,
> so that the outer loop that iterates over "it" would close
> the generator once the iteration is stopped.
>
> With your proposal you want to attach the opened file to the
> frame, but you'd need to attach it to the frame of *caller* of
> "it", right?
Every frame in the stack would still need to opt in to deterministic
cleanup of its resources, but the difference is that it becomes an
inline operation within the expression creating the iterator, rather
than a complete restructuring of the function:
def iter_consumer(fname):
for line in function_resource(open(fname)):
...
It doesn't matter *where* the iterator is being used (or even if you
received it as a parameter), you get an easy way to say "When this
function exits, however that happens, clean this up".
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list