title: How to delete multiple defined and undefined variables safely in python?
body: <p>I am currently using jupyter notebook, and I want to delete variables that are used only within the cell, so that I won't accidentally misuse these variables in other cells.</p>
  <p>For example, I want to remove the variable <code>myvar</code> and loop variable <code>i</code> in the following codes:</p>
  <pre><code>start = 1
  stop = 2
  for i in range(start, stop):
      pass
  myvar = &quot;A&quot;
  # other statements
  # ...
  del i, myvar # Runs ok, and variables i and myvar are deleted and I won't accidentally use i or myvar in another jupyter notebook cell
  </code></pre>
  <p>This works fine, but there are cases where some variables are actually not defined. In the following example, this throws an error since <code>i</code> is not defined because the loop is never run. The defined variables <code>myvar</code> is not deleted.</p>
  <pre><code>start = 1
  stop = 1 # Now we have stop equal to 1
  for i in range(start, stop):
      pass
  myvar = &quot;A&quot;
  # other statements
  # ...
  del i, myvar # NameError, since i is not defined, and myvar is not deleted
  </code></pre>
  <p>I have used contextlib or try-except statements to avoid the error, but still <code>myvar</code> is not deleted.</p>
  <pre><code>import contextlib
  start = 1
  stop = 1
  for i in range(start, stop):
      pass
  myvar = &quot;A&quot;
  # other statements
  # ...
  with contextlib.suppress(NameError):
      del i, myvar # Error suppressed, but myvar is not deleted
  </code></pre>
  <p>The only work-around is to wrap del statement for every variable I want to delete.</p>
  <pre><code>import contextlib
  start = 1
  stop = 1
  for i in range(start, stop):
      pass
  myvar = &quot;A&quot;
  # other statements
  # ...
  with contextlib.suppress(NameError): 
      del i
  with contextlib.suppress(NameError): 
      del myvar
  # ...
  # It works but codes get messy if I need to delete many variables
  </code></pre>
  <p>However, this makes codes messy, especially if you have a lot of variables to delete (n lines if there are n variables). Is there any way to delete all defined and undefined variables safely with less messy codes, in one/two lines?</p>