Rationale
Spillover of temporary variables can be a significant annoyance when working with Jupyter notebooks.
Aesthetically and logistically, it's bothersome to have a del var1, var2, var3
hanging around at the bottom
of a notebook cell to take care of cleanup of these temp variables. It prevents a Ctrl+End
from going to the end of relevant code, and if an Exception is raised in the course of code execution
the del
cleanup doesn't happen.
A short content manager class takes care of these various problems:
when execution leaves the with
suite, even due to a raised exception, the indicated variables are deleted.
Content manager class
class TempVars(object):
def __init__(self, *args):
self.varlist = args
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
ns = globals()
list(ns.pop(_) for _ in self.varlist if _ in ns)
return False
Usage
with TempVars('var1', 'var2', 'var3'):
var1 = 1
var2 = 'x'
var3 = [1, 2, 3]
var4 = 215
# The only surviving variable here will be var4