Let's simplify the question. Define:
def get_petters():
for animal in ['cow', 'dog', 'cat']:
def pet_function():
return "Mary pets the " + animal + "."
yield (animal, pet_function)
Then, just like in the question, we get:
>>> for name, f in list(get_petters()):
... print(name + ":", f())
cow: Mary pets the cat.
dog: Mary pets the cat.
cat: Mary pets the cat.
But if we avoid creating a list()
first:
>>> for name, f in get_petters():
... print(name + ":", f())
cow: Mary pets the cow.
dog: Mary pets the dog.
cat: Mary pets the cat.
What's going on? Why does this subtle difference completely change our results?
If we look at list(get_petters())
, it's clear from the changing memory addresses that we do indeed yield three different functions:
>>> list(get_petters())
[('cow', <function get_petters.<locals>.pet_function at 0x7ff2b988d790>),
('dog', <function get_petters.<locals>.pet_function at 0x7ff2c18f51f0>),
('cat', <function get_petters.<locals>.pet_function at 0x7ff2c14a9f70>)]
However, take a look at the cell
s that these functions are bound to:
>>> for _, f in list(get_petters()):
... print(f(), f.__closure__)
Mary pets the cat. (<cell at 0x7ff2c112a9d0: str object at 0x7ff2c3f437f0>,)
Mary pets the cat. (<cell at 0x7ff2c112a9d0: str object at 0x7ff2c3f437f0>,)
Mary pets the cat. (<cell at 0x7ff2c112a9d0: str object at 0x7ff2c3f437f0>,)
>>> for _, f in get_petters():
... print(f(), f.__closure__)
Mary pets the cow. (<cell at 0x7ff2b86b5d00: str object at 0x7ff2c1a95670>,)
Mary pets the dog. (<cell at 0x7ff2b86b5d00: str object at 0x7ff2c1a952f0>,)
Mary pets the cat. (<cell at 0x7ff2b86b5d00: str object at 0x7ff2c3f437f0>,)
For both loops, the cell
object remains the same throughout the iterations. However, as expected, the specific str
it references varies in the second loop. The cell
object refers to animal
, which is created when get_petters()
is called. However, animal
changes what str
object it refers to as the generator function runs.
In the first loop, during each iteration, we create all the f
s, but we only call them after the generator get_petters()
is completely exhausted and a list
of functions is already created.
In the second loop, during each iteration, we are pausing the get_petters()
generator and calling f
after each pause. Thus, we end up retrieving the value of animal
at that moment in time that the generator function is paused.
As @Claudiu puts in an answer to a similar question:
Three separate functions are created, but they each have the closure of the environment they're defined in - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though -- in this environment, animal
is mutated, and the closures all refer to the same animal
.
[Editor note: i
has been changed to animal
.]