How to delete a global variable from inside a function?

前端 未结 2 547
一个人的身影
一个人的身影 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: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
    

提交回复
热议问题