Skip to content

Instantly share code, notes, and snippets.

@bskinn
Last active June 23, 2023 09:43
Show Gist options
  • Save bskinn/bb7eac0c6af21fed4988a79169c73fd2 to your computer and use it in GitHub Desktop.
Save bskinn/bb7eac0c6af21fed4988a79169c73fd2 to your computer and use it in GitHub Desktop.
Python context manager for scrubbing of temporary variables in Jupyter notebook cells

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment