How to delete a global variable from inside a function?

前端 未结 2 528
一个人的身影
一个人的身影 2021-01-13 00:51

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

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

def reset_ser():
    pr         


        
相关标签:
2条回答
  • 2021-01-13 01:33

    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
    
    0 讨论(0)
  • 2021-01-13 01:35

    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
    
    0 讨论(0)
提交回复
热议问题