I have a question, which has arisen after running into an unexpected variable capture in a Python program I am working on.

Here is a sample:

def codeExample1(hashTable): def makeGenerator(): for keyName in hashTable: def valueGenerator(): for keyValue in hashTable[keyName]: yield keyValue yield (keyName,valueGenerator()) return makeGenerator()

Now, I was expecting keyName in the function valueGenerator to be bound to the value of keyName at the current step in the iterator over hashTable , effectively creating a new copy of the valueGenerator function each step.

What occurred instead was that keyName was bound to the value of keyName at the last step of the iterator, effectively making each valueGenerator call the same.

To correct this unexpected behavior, one would rewrite valueGenerator to take a parameter like this:

def codeExample1(hashTable): def makeGenerator(): for keyName in hashTable: def valueGenerator(_keyName): for keyValue in hashTable[_keyName]: yield keyValue yield (keyName,valueGenerator(keyName)) return makeGenerator()

So that was a bit of a long lead in, but what I'm trying to get at is what is the name for the type of variable capture exhibited by Python in this example and what is the name of the variable capture I was expecting to occur?