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

后端 未结 4 744
暖寄归人
暖寄归人 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:52

    The Python garbage collector isn't quite that smart. Even though you don't refer to cd any more after that line, the reference is still live in local variables, so it can't be collected. (In fact, it's possible that some code you're using might dig around in your local variables and resurrect it. Unlikely, but possible. So Python can't make any assumptions.)

    If you want to make the garbage collector actually do something here, try adding:

    del cd
    

    This will remove the local variable, allowing the object to be collected.

提交回复
热议问题