0

There's a python module module1.py, inside this module there was a class1, and a variable defined as x=class1() and y=class1(). After several operation the object x contained data.

How to write a function clean_up() in module1 such that

module1.clean_up() #takes no input argument

would reset x into the empty class1() and make y contain the value of x? I have tried to use

def clean_up():
    y=copy(x);
    del x;
    x=class1();

However, this does not make a copy of x and pass it to y, nor does it run successfully and clear x. An error returned as

module1.clean_up()
UnboundLocalError: local variable 'Hecke_variable' referenced before assignment

i.e. Both x and y were treated as local variables. But in a previous post, Python class instance changed during local function variable, class was mutable and any changes to a class instance inside a function would reflect outside the function as well.

Why wasn't the function clean_up() run successfully? How to write clean_up()?

1 Answers1

0

Variables defined in a function are bound to that function local scope. If you wish to affect variables in outer scope, you need to let python know by using the global keyword.

def clean_up():
    import copy

    global x, y

    y = copy.deepcopy(x)
    x = Class1()
collinsuz
  • 439
  • 1
  • 4
  • 13