12

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Dick Fagan
  • 131
  • 1
  • 1
  • 4

2 Answers2

20

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
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • Thanks a lot! Didn't know I had to declare it global inside the function. – Dick Fagan Dec 09 '17 at 18:30
  • 2
    Wow, three downvotes within 30 minutes to both answers, one day after being posted, without any explanation... did I miss something? – tobias_k Dec 09 '17 at 20:59
  • I swear I didn't downvote but this doesn't work for me. :) – markroxor Apr 18 '19 at 05:52
  • 1
    @markroxor Can you be more specific? "Does not work for me" as in "does not suit my use case", or "causes an exception"? In the latter case, what version of Python are you using? – tobias_k Apr 18 '19 at 09:46
11

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
ewcz
  • 12,819
  • 1
  • 25
  • 47
  • This is a very helpful answer. I have a big big python script and sometimes if things go wrong, the script sort of starts again from the main function. I needed a way to delete all the variables created so far and having the globals allows to easily and quickly delete them all. – Angelo Mar 29 '19 at 21:38