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?

3
  • 4
    You forgot to declare ser as global in the function. Commented Dec 8, 2017 at 15:26
  • Why do you have to delete ser? Why not just clear it, eg ser.clear()? Commented Dec 8, 2017 at 15:28
  • 5
    Note, doing global some_var in the global scope is totally useless. Commented Dec 8, 2017 at 17:57

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot! Didn't know I had to declare it global inside the function.
Wow, three downvotes within 30 minutes to both answers, one day after being posted, without any explanation... did I miss something?
I swear I didn't downvote but this doesn't work for me. :)
@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?
12

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.