Okay, bear with me on this, I know it's going to look horribly convoluted, but please help me understand what's happening.
from functools import partial
class Cage(object):
def __init__(self, animal):
self.animal = animal
def gotimes(do_the_petting):
do_the_petting()
def get_petters():
for animal in ['cow', 'dog', 'cat']:
cage = Cage(animal)
def pet_function():
print "Mary pets the " + cage.animal + "."
yield (animal, partial(gotimes, pet_function))
funs = list(get_petters())
for name, f in funs:
print name + ":",
f()
Gives:
cow: Mary pets the cat.
dog: Mary pets the cat.
cat: Mary pets the cat.
So basically, why am I not getting three different animals? Isn't the cage
'packaged' into the local scope of the nested function? If not, how does a call to the nested function look up the local variables?
I know that running into these kind of problems usually means one is 'doing it wrong', but I'd like to understand what happens.
question from:https://stackoverflow.com/questions/65546104/passing-lambda-functions-arguments-via-loop