S
Stefan Bellon
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!
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!