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
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.