Reputation: 163
Is there a command I can use in a Python file to clear all variables?
I've been searching for this for a while but all I could find was to use %reset
. However, this only seems to work in IPython, but not when I try to run a python file.
FYI, I am working with the free version of enthought canopy.
[ADDED from comments:] I have several python files I run, which might have shared variables. I would like to be able to clear all variables before running any of the files to guarantee that I have defined variables correctly and that they are taking the correct values.
Upvotes: 0
Views: 1872
Reputation: 5810
tl;dr -- what you describe is not an issue.
But it is worth understanding, to avoid other points of confusion:
1) When you are running IPython (including Canopy's Python pane, which is a standard IPython QtConsole), IPython has its own global namespace (list of variables and modules and functions etc) which is distinct from the namespace of the scripts which run within it. This can be confusing, but it is actually a feature.
2) When you run each script normally, it starts with an empty namespace, just as if it were running in plain Python. That's why your concern is a non-issue. But this can also confuse beginners, because your script also doesn't know about the modules that have already been imported in IPython. For more on this, see this article.
3) When the script completes, its global namespace is copied into the IPython global namespace (overwriting any same-named variables that were already there).
4) Thus normal visibility is one-way -- IPython sees the results of the scripts that you ran, so you can work with them more at the prompt, but your scripts don't see the results of previous scripts that you ran (not even the same script), or of anything you do at the prompt.
5) There is one huge difference, though, from when you run your script in plain Python. Namely, IPython itself is not re-initialized between runs (unless you reset the kernel), and in particular, any modules that have been imported are still initialized and won't be re-loaded or re-initialized when you import them in subsequent scripts. For more info, see this article.
6) A side note: The %run command can be given a -i
option to make namespace visibility 2-way, so your scripts will start in the IPython namespace (as I think you were expecting), but this is unusual and not the default, since usually one wants to ensure (as you apparently do) that the script is running "clean". The main reason to use this option would be to have your scripts build on each other, but there are more robust, portable ways to achieve this (namely passing variable names from the IPython namespace as parameters to the functions that you define in your script).
Upvotes: 1