Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a global variable from inside a function?

I have a global variable ser which I need to delete under certain circumstances:

global ser
ser = ['some', 'stuff']

def reset_ser():
    print('deleting serial configuration...')
    del ser

If I call reset_ser() I get the error:

UnboundLocalError: local variable 'ser' referenced before assignment

If I give the global variable to the function as an input I do not get the error, but the variable does not get deleted (I guess only inside the function itself). Is there a way of deleting the variable, or do I e.g.have to overwrite it to get rid of its contents?

like image 512
Dick Fagan Avatar asked Dec 08 '17 15:12

Dick Fagan


People also ask

How do you delete a global variable?

To delete a global variable from the global variable list, move the cursor to the line that contains the variable name and press the Delete function key.

How do I change a global variable inside a function?

Use of “global†keyword to modify global variable inside a function. If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.

How do you delete a global in Python?

You can change the value of a Python global variable by simply assigning it a new value (redeclaring). To delete a variable, use the keyword del .

How do you clear a global variable in C++?

you can put those variables in aclass , then create pointer to object of that class in the 1st place will use those variables then pass this pointer to every methode need those variables , don`t forget to delete the object when you will not use .


2 Answers

you could remove it from the global scope with:

del globals()['ser']

a more complete example:

x = 3

def fn():
    var = 'x'
    g = globals()
    if var in g: del g[var]

print(x)
fn()
print(x) #NameError: name 'x' is not defined
like image 185
ewcz Avatar answered Oct 17 '22 15:10

ewcz


Just use global ser inside the function:

ser = "foo"
def reset_ser():
    global ser
    del ser

print(ser)
reset_ser()
print(ser)

Output:

foo
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print(ser)
NameError: name 'ser' is not defined
like image 18
tobias_k Avatar answered Oct 17 '22 17:10

tobias_k