0

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?

merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • 2
    This isn't really specific to globals. The same thing would happen for any lambda defined in a loop. Related reading: [Why do lambdas defined in a loop with different values all return the same result?](https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result) – Kevin May 08 '18 at 18:44
  • @Kevin, Thanks for the link. Will read up. – merlin2011 May 08 '18 at 18:47

0 Answers0