I am using Spyder for exploratory data analysis -- not for production code. I like to think of my script as a sequence of major sections. At the end of each section, I want to delete the temporary objects so that the Variable Explorer in Spyder isn't too crowded. However, the objects that exist depend on the control flow through the code. If I have just one del
statement at the end of each section to delete all objects that may come into existence regardless of the control flow through the code, I get NameError
for those objects that haven't been created.
Is there a simple one-liner that I can use, similar to del a,b,c,d
but not yielding an error if some of the variables don't exist? I want a short one-liner because I don't want to take attention away from the main functions of the code.
A try/except block is a multi-line control structure that contributes too much cognitive noise to the code, in my opinion. Something like the following doesn't seem legal, and it seems to be that a one-liner can't consist of an if-statement within a for-loop:
# Syntax error at the "if"
for vName in ['gbCluster']: if vName in locals(): del locals()[vName]
# Works without "if"
for vName in ['gbCluster']: del locals()[vName]
Use a function! You can pass in the namespace (dict) that you want names (keys) deleted from, and the function can do the heavy lifting of deleting and ignoring errors. You can then put the function in a module for reuse.
By the way, the names you want to delete are globals, not locals per se (and anyway you shouldn't modify locals()
).
def del_keys_noerror(d, *keys):
for key in keys:
try:
del d[key]
except KeyError:
pass # Ignore keys that are already absent
For example:
a = False
if a:
b = 0
del_keys_noerror(globals(), 'a', 'b')
Result: a
gets deleted, b
gets ignored
P.S. I suggest logging when a name is already undefined vs successfully deleted, just in case you need to debug the function.