I want to analyze a game using minimax with alpha-beta pruning in python. The pseudocode will be something like
def alphabeta(node, depth, alpha, beta, isMaxNode):
blah blah
for each child of node
blah blah
In this particular game, calculating the children of a node is rather complicated, so I'd like to define a generator
def children(node):
blah blah
yield child
and then have
for child in children(node)
as the implementation of the for loop above.
I'm worried about what happens when an alpha-beta cutoff occurs, so that there is a break in the for each child loop, and we never get to the end of the generator. What happens to the closure? Is it garbage collected, or will I have a bunch of unresolved closures chewing up the memory?
It seems like I should know the answer to this. I would think that the closure goes out of scope when the break occurs, and becomes eligible for garbage-collection, but I'm not sure.
This is different from Will a Python generator be garbage collected if it will not be used any more but hasn't reached StopIteration yet?
In that question, the generator has not gone out of scope, and the compiler would have to read the code and determine that the generator isn't called again. It seems to me, however, that in the case I pose in this question, the generator should be out of scope and eligible for garbage collection once a break occurs in the for loop. Is that right?
EDIT
Looking at the code again, I realize that once an alpha-beta cutoff, the function alphabeta not only breaks out of the for loop, it returns. That makes it seem even more likely that generator object would be garbage-collected, but I don't know anything about the details of the cPython implementation.