Will a Python generator be garbage collected if it will not be used any more but hasn't reached StopIteration yet?

后端 未结 4 748
暖寄归人
暖寄归人 2020-12-31 01:12

When a generator is not used any more, it should be garbage collected, right? I tried the following code but I am not sure which part I was wrong.

import wea         


        
4条回答
  •  死守一世寂寞
    2020-12-31 01:55

    The other answers have explained that gc.collect() won't garbage collect anything that still has references to it. There is still a live reference cd to the generator, so it will not be gc'ed until cd is deleted.

    However in addition, the OP is creating a SECOND strong reference to the object using this line, which calls the weak reference object:

    cdw = weakref.ref(cd)()
    

    So if one were to do del cd and call gc.collect(), the generator would still not be gc'ed because cdw is also a reference.

    To obtain an actual weak reference, do not call the weakref.ref object. Simply do this:

    cdw = weakref.ref(cd)
    

    Now when cd is deleted and garbage collected, the reference count will be zero and calling the weak reference will result in None, as expected.

提交回复
热议问题