Pedr Bergfalk
Pedr Bergfalk

Reputation: 131

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?

Upvotes: 12

Views: 24664

Answers (2)

tobias_k
tobias_k

Reputation: 82899

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

Upvotes: 20

ewcz
ewcz

Reputation: 13087

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

Upvotes: 12

Related Questions