Search code examples
pythonfunctionglobal-variables

Why is my function editing an variable i didnt specify?


print(generated)
grid = Main(generated,boxes)
print("gnen")
print(generated)
print("grid")
print(grid)

For context: this is a sudoku generator and Main() solves a sudoku and returns a solved sudoku. However generated is edited.

Any help would be deeply appreciated!


Solution

  • You are mutating the generated in the function you shouldn't do that add this line at the top of the file

    import copy
    

    and then edit the function Main as this

    def Main(your_variable_name_here, your_variable_name_here2):
        your_variable_name_here_ = copy.deepcopy(your_variable_name_here)
    

    change this across all your Main function i.e after editing the function use your_variable_name_here_ and not your_variable_name_here

    https://docs.python.org/3/library/copy.html#copy.deepcopy