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,955
  • 8
  • 40
  • 71
  • The reason that copying doesn't help is because the problem isn't caused by "references", it's caused by late binding. The copy would only happen after looking up the name, which happens when `fun_with_parameters` is *called*, not when it's created. – Karl Knechtel Aug 19 '22 at 12:38

1 Answers1

2

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
  • 705
  • 3
  • 11