0

I am having difficulty dynamically creating functions in python. Suppose I have 2 dictionaries, dict_1 and dict_2, and I am iterating through the dictionaries to create functions based on the individual elements (1, 2, 3, 7, 8, 9). Each function is meant to be unique and should be able to print a unique output when called. The unique functions are then added to a dictionary which stores all the functions. However, when the below code is executed, the print outputs are all the same.

dict_1 = [1, 2, 3] 
dict_2 = [7, 8, 9]

def create_functions_dict():
  count = 1
  functions_dict = dict()
  for a in dict_1:
    var_one = a
    for b in dict_2:
      var_two = b

      def new_dynamic_func():
          print (var_one, var_two)
          return 

      name = "function" + str(count)
      functions_dict[name] = new_dynamic_func
      count += 1

  return functions_dict


dict_of_functions = create_functions_dict()
print (dict_of_functions)

when the above code is executed, this is the following output, proving the functions are unique?

{'function1': <function create_functions_dict.<locals>.new_dynamic_func at 0x00000214D54343A0>, 'function2': <function create_functions_dict.<locals>.new_dynamic_func at 0x00000214D54D7DC0>, 'function3': <function create_functions_dict.<locals>.new_dynamic_func at 0x00000214D7413160>, 'function4': <function create_functions_dict.<locals>.new_dynamic_func at 0x00000214D7413280>, 'function5': <function create_functions_dict.<locals>.new_dynamic_func at 0x00000214D7413310>, 'function6': <function create_functions_dict.<locals>.new_dynamic_func at 0x00000214D74133A0>, 'function7': <function create_functions_dict.<locals>.new_dynamic_func at 0x00000214D7413430>, 'function8': <function create_functions_dict.<locals>.new_dynamic_func at 0x00000214D74134C0>, 'function9': <function create_functions_dict.<locals>.new_dynamic_func at 0x00000214D7413550>}

However, when the below code is executed, the output shows that all the functions are the same

for i in dict_of_functions:
  function = dict_of_functions[i]
  print (function())

code output

3 9
None
3 9
None
3 9
None
3 9
None
3 9
None
3 9
None
3 9
None
3 9
None
3 9
None

How do I get the variables issued in the for loops to remain in the dictionary of functions? ie, how do I get the output print to be "1, 7", "1, 8", "1, 9", "2, 7", "2, 8", "2, 9", "3, 7", "3, 8", "3, 9"?

Dustyik
  • 69
  • 1
  • 6

0 Answers0