0

In python I can use the nonlocal keyword to make sure that I use the variable from the outer scope, but how do I copy the variable from the outer scope into the closure?

I have code like this:

my_functions_with_parameters = []
for fun_name in my_function_names:
    fun = my_functions[fun_name]
    def fun_with_parameters():
        return fun(1,2,3)
    my_functions_with_parameters.append(fun_with_parameter)

My problem is, that each instance of fun_with_parameters calls the last function, i.e., my_functions[my_function_names[-1]], because the variable fun is a reference.

I tried to use fun = copy.deepcopy(my_functions[fun_name]) but it did not change anything and is probably not the best or fastest way.

allo
  • 3,515
  • 5
  • 35
  • 64

1 Answers1

1

Try this instead:

my_functions_with_parameters = []
for fun_name in my_function_names:
    fun = my_functions[fun_name]
    my_functions_with_parameters.append(fun)

Now you can provide the parameters to each fun in my_functions_with_parameters when you loop through them:

for my_fun in my_functions_with_parameters:
    my_fun(1,2,3)

Or you can store the parameters with the function in a tuple:

my_functions_with_parameters = []
for fun_name in my_function_names:
    fun = my_functions[fun_name]
    my_functions_with_parameters.append((fun, 1, 2, 3))

And call via:

for tup in my_functions_with_parameters:
    tup[0](tup[1], tup[2], tup[3])
afghanimah
  • 695
  • 2
  • 11