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?
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.
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.
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 .
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 .
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With