[Python-ideas] Deterministic iterator cleanup

Chris Angelico rosuav at gmail.com
Wed Oct 19 16:16:52 EDT 2016


On Thu, Oct 20, 2016 at 7:14 AM, Neil Girdhar <mistersheik at gmail.com> wrote:
> class AddIterclose:
>
>     def __init__(self, iterable, iterclose):
>         self.iterable = iterable
>         self.iterclose = iterclose
>
>     def __iter__(self):
>         try:
>             for x in self.iterable:
>                 yield x
>         finally:
>             self.iterclose()

Can this be simplified down to a generator?

def AddIterclose(iterable, iterclose):
    try:
        yield from iterable
    finally:
        iterclose()

ChrisA


More information about the Python-ideas mailing list