Issue
With del a, b, c
I can delete 3 variables at once if all variables a, b, c
exist. However if a variable does not exists I get an error.
If I would like to delete variables a, b, c
I could beforehand manually check its existence:
a = 1
b = 1
if 'a' in locals(): del a
if 'b' in locals(): del b
if 'c' in locals(): del c
This is quite cumbersome as I often want to delete multiple variables. Is there a more comfortable way similar to del a, b, c
?
Why do I want to delete variables?
The Variable Explorer (e.g. in Spyder or other IDE) lists all my variables. For better overview I want to see only the important variables. Temporary variables that are used only for auxiliary purpose are not needed later and therefore do not have to appear in the Variable Explorer. Also memory is freed if auxiliary variables are deleted.
Solution
A initialized variable, a = 1
, is stored as a key-value pair, {"a": 1}
, in a dictionary which is accessible via locals
, globals
built-ins.
Use dict.pop
with a default value to remove the variable.
It is better to work with care when operating on locals()
, globals()
dictionaries, see comment of Mark Tolonen for details and reference to the doc.
#variables initialization
x1, x3 = 1, 3
# variables identifiers
to_del = "x1", "x2", "x3"
# delete the variables
for var_id in to_del:
globals().pop(var_id, None)
# check
print(x1)
#NameError
EDIT: from the comment, in the form of a function
def g_cleaner(to_del:list[str]) -> None:
"""global cleaner"""
for var_id in to_del:
globals().pop(var_id, None)
g_cleaner(to_del)
print(x1)
#NameError: name 'x1' is not defined
alternative version
def g_cleaner(*to_del:list[str]) -> None:
"""global cleaner"""
for var_id in to_del:
globals().pop(var_id, None)
# for list-like arguments (unpacking)
g_cleaner(*to_del)
print(x1)
#NameError: name 'x1' is not defined
# for specific values
g_cleaner("x1", "x2") # quotes are needed!
print(x1)
#NameError: name 'x1' is not defined
Answered By - cards
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.