Enhancement: add option to "clear all" variables before running script
See original GitHub issueI can define a variable in the console and have that same variable be available in script; the equivalence of Matlab’s clear all
isn’t an option in preferences.
That is, at the IPython prompt I can define a = 10
. Then if my script contains one line,
# script.py
print(a) # prints 10 even though `a` is not defined *in script*
It’d certainly be nice to disable that behavior. Other interpreters (e.g., default Python, IPython’s %run
) don’t have this behavior enabled – it throws NameError: name 'a' is not defined
. Matlab has this feature where it reads variables defined from the variable explorer (and not the script) but it can be easily disabled with clear all
. In Spyder, it requires a clever hack to “clear all”.
Proposed solution
Under “Run preferences” or in Spyder preferences > Run, I propose an option to enable/disable the equivalent of Matlab’s “clear all”. I propose the wording/default option be something like “[x] Variables in script must be defined in script. Otherwise, variables must be defined in Variable Explorer.”
Current hack
In the settings under IPython console > Startup, I have enabled a file to be run whenever I run a file. That file consists of a script to clear all the variables (which I found here):
def clear_all():
"""Clears all the variables from the workspace of the spyder application."""
gl = globals().copy()
for var in gl:
if var[0] == '_': continue
if 'func' in str(globals()[var]): continue
if 'module' in str(globals()[var]): continue
del globals()[var]
if __name__ == "__main__":
clear_all()
Details: I’m running Spyder 2.3.5.2
Issue Analytics
- State:
- Created 8 years ago
- Reactions:2
- Comments:14 (9 by maintainers)
See https://gist.github.com/scottsievert/8655158355b7155b2dd8
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
Two things:
%reset
magic.Execute in a new dedicated Python console
(which you can get when pressing F6) always run your code in a clean interpreter, every time.Do we need to offer our users something else than that? I mean, when you run your code in the current Python or IPython console, it’s assumed that it’s going to pick up whatever values that are present there 😃