Destruction of generator objects

MRAB google at mrabarnett.plus.com
Wed Aug 8 18:44:04 EDT 2007


On Aug 7, 11:28 pm, Stefan Bellon <sbel... at sbellon.de> wrote:
> Hi all,
>
> I'm generating a binding from Python to C using SWIG. On the C side I
> have iterators over some data structures. On the Python side I
> currently use code like the following:
>
>     def get_data(obj):
>         result = []
>         iter = make_iter(obj)
>         while more(iter):
>             item = next(iter)
>             result.append(item)
>         destroy(iter)
>         return result
>
> Now I'd like to transform it to a generator function like the following
> in order to make it more memory and time efficient:
>
>     def get_data(obj):
>         iter = make_iter(obj)
>         while more(iter):
>             yield next(iter)
>         destroy(iter)
>
> But in the generator case, I have a problem if the generator object is
> not iterated till the StopIteration occurs, but if iteration is stopped
> earlier. In that case, the C iterator's destroy is not called, thus the
> resource is not freed.
>
> Is there a way around this? Can I add some sort of __del__() to the
> generator object so that in case of an early destruction of the
> generator object, the external resource is freed as well?
>
> I'm looking forward to hearing your hints!
>
> --
> Stefan Bellon

Simple! :-)

def get_data(obj):
    iter = make_iter(obj)
    try:
        while more(iter):
            yield next(iter)
    finally:
        destroy(iter)




More information about the Python-list mailing list