Skip to content

Instantly share code, notes, and snippets.

@stsievert
Last active September 25, 2022 11:39
Show Gist options
  • Save stsievert/8655158355b7155b2dd8 to your computer and use it in GitHub Desktop.
Save stsievert/8655158355b7155b2dd8 to your computer and use it in GitHub Desktop.
clear all variables/reset for Spyder

Spyder's default

Spyder does not clear all variables before running a script in the IPython prompt. If you define x = 10 at the IPython prompt (not in script) and your file script.py is

# FILE: script.py
print(x)

it will print 10.

This is not default Python behavior. When Spyder runs a file, it uses a function called run_file that enables this behavior. I use IPython's %run which throws errors if variables are not defined in script but the console can still see variables from a script.

Workarounds

There must be ways around this! There have to be. Any one of these ways work and clear all variables.

IPython magic %reset

At the IPython prompt, %reset clears everything -- it's like you're starting up the shell again. This way works and has to be manually run at the IPython prompt.

If you want to do it every run, at the very top of your script insert

from IPython import get_ipython
get_ipython().magic('reset -sf')

(Recommended method) I don't want to insert something so long at the top of my file every time -- how about something shorter and easier to remember?

To do that, I would download SSreset.py (below, downloadable) and put it somewhere it won't be moved around (like in my Documents folder -- I never touch that). In Spyder > Preferences > IPython console > Startup I would specify to run SSreset.py on startup. At the top of each script, I would include the line __reset__(), giving me something like

__reset__()
from pylab import *

x = linspace(0, 1)
y = exp(x)

figure()
plot(x, y)
show()

I want to be clear: by default, Python does not show this behavior with variables.

Dedicated console

Scripts can be run in a dedicated Python console. Unfortunately, this does not give you interactivity (you can't type plot(x**3); show() at the prompt to see what x looks like; there is no prompt!

Pop ups

Little yellow warnings pop up to undefined variables. Unfortunately, from pylab import * disables this but there's an example below.

Details

I am running Spyder 2.3.5.2. This behavior might change in the future -- I made a related related Github issue

from IPython import get_ipython
def __reset__(): get_ipython().magic('reset -sf')
@stsievert
Copy link
Author

The example for the little notification for undefined variable:

undefined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment