7

I am an absolute beginner in Python. I have been using R and Matlab for data analysis for quite some time. One of the great things about these languages (or tools) is that I could run clear all in Matlab or rm(list=ls()) in R to clear the variables I created. I could then continue to experiment with my snippet of code.

I am struggling to find such a solution in Python. I researched Is there a way to delete created variables, functions, etc from the memory of the interpreter? and found that there are two ways to accomplish what I am trying to do, but in reality they are not any close.

First method:

%Reset

This command deletes all variables and imported setting in PyCharm to run interactive mode. That is, after running above command, I have to re-run

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

This is very annoying.

Second Method:

Another suggested method is to write a for loop and ignore functions starting with __. This also doesn't work for the reasons above. For instance, when I start my PyCharm, I run

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

to ensure that I am able to run a bunch of commands together just as I would do in Matlab and R (In PyCharm, the keyboard shortcut is [Alt + Shift + E; This is called as Execute Selection in Console]). I have noticed that the for loop mentioned in that Stackoverflow thread deletes some of the variables created by running above two lines of code. This means that I won't be able to execute statements by selecting them at a time. I would have to type them individually on the prompt, which is annoying. Another option would be to run above two lines of code every time I execute the for loop, which is annoying as well.

As an aside, I did some research to understand what happens after running above two lines of code. I ran dir() after running above two lines to get a list of all variables existing in my session.

The list looks like this

Out[4]: 
['In',
 'InteractiveShell',
 'Out',
 '_',
 '_2',
 '__',
 '___', 
......(continued)
 'sys']

Is there any way, I can delete user-created variables without deleting above variables? In effect, I want to replicate what rm(list=ls()) would do for me in R.

I see that there are a number of people who have asked this question outside StackOverflow such as https://github.com/spyder-ide/spyder/issues/2563.

Thanks for any help. I am using PyCharm with the latest Conda distribution (3.6).

Wolfie
  • 27,562
  • 7
  • 28
  • 55
watchtower
  • 4,140
  • 14
  • 50
  • 92
  • you might not need to. Look up garbage collection for python. For other languages, when a variable goes out of view, garbage collection gets rid of it automatically. – Bindrid Jan 14 '18 at 22:25
  • 3
    This sound like an [XY problem](https://meta.stackexchange.com/a/66378). Why do you actually want to do this? – Klaus D. Jan 14 '18 at 22:27
  • @Bindrid and Klaus D. - To give you some background, R and Matlab let us execute statements by selecting them at a time rather than entering them one by one. This is very convenient when I am testing a bunch of statements. I have asked this question at https://stackoverflow.com/questions/47964128/executing-multi-line-statements-in-python-in-interactive-mode and at https://stackoverflow.com/questions/47984045/display-output-of-every-line-in-pycharm-python. Above two lines were suggested by an expert there. I'd appreciate your help. – watchtower Jan 14 '18 at 22:35
  • Basic problem is that python does not really have variables. It has objects. Which pretty much covers everything. – Stephen Rauch Jan 14 '18 at 22:36
  • @Stephen - Thanks. Given what you said, how do I accomplish what I am looking for? I'd appreciate your thoughts. – watchtower Jan 14 '18 at 22:38
  • I almost never use IPython anymore. Or interactive shell at all. I just write small scripts. And then edit them and run them again. Start fresh everytime... – Stephen Rauch Jan 14 '18 at 22:40
  • 4
    @StephenRauch really, this is an issue of PyCharm integration with IPython. IPython works just fine to accomplish what the OP wants. It is an interactive shell geared towards data-analysis, thus it has a "clear-all-user-variables" functionality. However, this also swallows PyCharm variables. The problem here is that PyCharm isn't really a tool geared towards this sort of programming, it is more geared towards production level software engineering. OP: you should consider maybe IPython notebooks, or the Spyder IDE which is a lot like RStudio. – juanpa.arrivillaga Jan 14 '18 at 22:48
  • 1
    even in R I strongly suggest against having a workflow that requires running `rm(list=ls())`. you should be comfortable (in rather language) with completely restarting your session (saving to disk the most time-consuming bits of code you've already run): https://www.tidyverse.org/articles/2017/12/workflow-vs-script/ – MichaelChirico Jan 14 '18 at 23:55
  • @MichaelChirico absolutely, you should be organized enough were this isn't necessary. – juanpa.arrivillaga Jan 15 '18 at 02:51
  • @MichaelChirico - I believe Hadley has clarified his assumption in his article: `Caveat: ... The importance of these practices has a lot to do with whether your code will be run by other people, on other machines, and in the future. If your current practices serve your purposes, then go forth and be happy.` I agree with Hadley. If my code were to be used by others, I would create a subroutine. I have a specific use case: to test snippet of code without having to run the entire script. This type of experimentation helps during early stages of code design and even learning any language. – watchtower Jan 15 '18 at 03:13
  • "current practices serve your purposes" seems belied by the existence of this question TBH – MichaelChirico Jan 15 '18 at 04:12

4 Answers4

10

Try this:

>>> x = 1
>>> x
1
>>> globals().clear()
>>> x
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    x
NameError: name 'x' is not defined

Note that the the docs don't actually say that you can safely modify the dictionary that globals() returns, nor that modifying this dictionary will have the effect you intend (or any effect at all). But if you're just doing it for convenience in the REPL, then if it works, it works.

kaya3
  • 47,440
  • 4
  • 68
  • 97
2

If you wish to simply clear all variables you've defined in the console.. That is to undo everything your code has done and 'start fresh'..

Type:

exit

in the console

In Spyder this simply clears the workspace of anything your code has done. The same effect as closing and restarting Anaconda, but without having to do so. Now you can run your code with a fresh workspace!

def_proxy
  • 41
  • 5
0

How about running the code in "Interactive mode" in VSC? You can close the interactive window to erase all the value of the variables.

Anil Kamat
  • 1
  • 1
  • 1
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31296715) – Manuel Fedele Mar 18 '22 at 12:43
0

Using PyCharm 2021.3.3 (Community Edition) built March 16. 2022: There are two columns of buttons on the left of the console the bottom left one says "New Console" on hover. Pressing it gives a new console (duh) with no user variables.

Steve Maguire
  • 393
  • 1
  • 4
  • 11