Clearing python global variables

I recently took a class on scripting ArcGIS with python. We were doing exercises in PythonWin and were constantly running and rerunning scripts into the same interpreter. So any variables from the last script would still be set in the interpreter’s globals(). Most would get overwritten, but some actually caused the programs to act weird. To remedy this, they had us use ‘del’ statements on our variables at the end of each script. This seemed like a waste of time and got really old fast. I looked around for a function that clears all global variables but was met with posts telling me that python garbage collection takes care of it, well, not in this situation. This was the remedy I came up with on my down time:

#
def clearall():
    """clear all globals"""
    for uniquevar in [var for var in globals().copy() if var[0] != "_" and var != 'clearall']:
        del globals()[uniquevar]

if you put this in a script and run it once, or directly into the interpreter, you can call the clearall() function from anywhere. It also makes sure not to delete itself. It’s not perfect but works well in most situations.

0 comments ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment