I am attempting to create module-level functions dynamically in a loop using the globals()
array, but it looks like all the functions I create point to the last function defined in the loop.
Consider the following example.
import sys
arr = ["Magic1", "Magic2"]
for magic in arr:
print magic
globals()[magic.upper()] = lambda x: sys.stdout.write(x + magic + '\n')
MAGIC1("foo")
MAGIC2("foo")
Actual output:
Magic1
Magic2
fooMagic2
fooMagic2
Desired output:
Magic1
Magic2
fooMagic1
fooMagic2
What did I do incorrectly, and how can I get the previous function definitions in the loop to stick?