-1

I have two variables (variable_1 and variable_2). They are outputs of an algorithm and they are always different, since the algorithm contains some random part.

And I have a very long and complex function afterwards, that takes these variables as inputs. Its basic structure is:

def function(variable_1, variable_2):
    switch = True
    while switch:
      variable_1
      variable_2
      inner_function(variable_1, variable_2):
         ~changes variable_1 and variable_2 randomly~
      ~changed variable_1 and variable_2 are then transformed with data structure comprehensions.~
      ~in the end, there is a condition. If variable_1 and variable_2 meet this condition, switch is turned to False and the function ends. If not, the while loop shall start again, but with the original values of variable_1 and variable_2.~

The intention of the function is to output the changed variables. The problem is that it does not work. If the while loop runs through one iteration, and the switch is still True at the end of this iteration, variable_1 and variable_2 are not set back to their original values. How can I do this? (Please keep in mind that I do not want to fix variable_1 and variable_2 for my entire code that comes before or afterwards).

Sorry for not giving a minimally reproduceable example. I could not come up with one, considering the length and complexity of the function.

Edit: If I hardcode the variables (meaning that I write variable_1 = "its value" and variable_2 = "its value" above the inner function, it works. But I do not want to do this.

lonyen11
  • 91
  • 11

2 Answers2

1

So you just need to make a deepcopy:

import copy

def function(variable_1o, variable_2o):
    switch = True
    while switch:
      variable_1 = copy.deepcopy(variable_1o)
      variable_2 = copy.deepcopy(variable_2o)
      inner_function(variable_1, variable_2)
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

Here you actually asking: "How to pass variables by value, not by reference".
One of approaches to do this is to put the original variables to the list, then to create another list from that list, and then to pass the second list as a parameter to the function. This will imitate passing variables by value, not by reference.
Like following:

def function(variable_1, variable_2):
original_list = [variable_1, variable_2]
    switch = True
    while switch:
      copy_list = original_list[:]      
      inner_function(copy_list):
      #here you can use, change etc the data in copy_list safely
         ~changes variable_1 and variable_2 randomly~
      ~changed variable_1 and variable_2 are then transformed with data structure comprehensions.~
      ~in the end, there is a condition. If variable_1 and variable_2 meet this condition, switch is turned to False and the function ends. If not, the while loop shall start again, but with the original values of variable_1 and variable_2.~
Prophet
  • 32,350
  • 22
  • 54
  • 79