Issue
I have a long ipynb file. I want to periodically clean namespace from variables that I do not need further in a notebook.
I wrote an utility function for that:
def clean_namespace(variables_to_delete):
deleted = []
for variable in variables_to_delete:
if variable in globals():
del globals()[variable]
deleted.append(variable)
return deleted
The function works fine, it deletes all existing variables from the given list of variable names.
If I want to use it in multiple jupyter notebooks, it is logical to put its definition in a module, lets say `my_utils.py'.
However, if I try:
from my_utils import clean_namespace
clean_namespace(['var1','var2'])
It does not delete anything, even if 'var1' exist in the notebook in the moment of calling.
I understood from @Steven Scott's comment on this answer that globals() gives variables defined in the module where a function resists, but I find convenient to have such a function in my toolbox and not to have to define it again in each notebook.
Is there an elegant way to have this functionality? Should I pass some additional argument?
Solution
I would rather pass the scope in the function. Modify the code like this:
def clean_namespace(scope, variables_to_delete):
deleted = []
for variable in variables_to_delete:
if variable in scope:
del scope[variable]
deleted.append(variable)
return deleted
Then I will call it like this:
from my_utils import clean_namespace
clean_namespace(globals(), ['var1','var2'])
This will ensure that your variables are cleaned up from the scope of your module only.
Answered By - Mukul Bindal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.