Automatically remove generator object from memory at StopIteration (Python)
I noticed once a generator is exhausted, the object remains in memory. How can I make the generator o开发者_StackOverflow中文版bject automatically remove itself from memory once it is exhausted?
You could try making a wrapper generator that makes sure it doesn't have a reference to the inner generator once it finishes. The following might even do it (completely untested):
def strange(gen):
for thing in gen:
yield thing
Once gen
raises StopIteration
the strange
generator will exit the for loop and then return None
, which will again raise StopIteration
. If gen
was the last reference to the generator, it should/might be available to be garbage collected before whatever code is iterating over strange(gen)
gets control back. On CPython that would mean it is freed.
Note that that won't help if you do something like the following:
g = some_generator()
for x in strange(g):
do_something()
Because g
itself is a reference to the inner generator. You'd have to be using it more like this:
for x in strange(some_generator()):
do_something()
But really, the simplest method is to do what you do with any other object when you don't want it to hang around in memory: make sure you're not holding on to a reference to it. If the variable referencing it was in a long lived scope, you can explicitly del
it.
This is not an operation supported by Python.
精彩评论