[Python-ideas] Deterministic iterator cleanup
Oscar Benjamin
oscar.j.benjamin at gmail.com
Wed Oct 19 07:39:26 EDT 2016
On 19 October 2016 at 12:33, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
>
>> New convenience functions
>> -------------------------
>>
>> The ``itertools`` module gains a new iterator wrapper that can be used
>> to selectively disable the new ``__iterclose__`` behavior::
>>
>> # XX FIXME: I feel like there might be a better name for this one?
>> class protect(iterable):
>> def __init__(self, iterable):
>> self._it = iter(iterable)
>>
>> def __iter__(self):
>> return self
>>
>> def __next__(self):
>> return next(self._it)
>>
>> def __iterclose__(self):
>> # Swallow __iterclose__ without passing it on
>> pass
>>
>> Example usage (assuming that file objects implements ``__iterclose__``)::
>>
>> with open(...) as handle:
>> # Iterate through the same file twice:
>> for line in itertools.protect(handle):
>> ...
>> handle.seek(0)
>> for line in itertools.protect(handle):
>> ...
>
> It would be much simpler to reverse this suggestion and say let's
> introduce a helper that selectively *enables* the new behaviour you're
> proposing i.e.:
>
> for line in itertools.closeafter(open(...)):
> ...
> if not line.startswith('#'):
> break # <--------------- file gets closed here
Looking more closely at this I realise that there is no way to
implement closeafter like this without depending on closeafter.__del__
to do the closing. So actually this is not a solution to the problem
at all. Sorry for the noise there!
--
Oscar
More information about the Python-ideas
mailing list