The Python Oracle

How to clear variables in ipython?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Island

--

Chapters
00:00 Question
00:29 Accepted answer (Score 258)
00:42 Answer 2 (Score 70)
01:39 Answer 3 (Score 65)
01:53 Answer 4 (Score 23)
02:18 Thank you

--

Full question
https://stackoverflow.com/questions/2293...

Answer 1 links:
[https://regexone.com/]: https://regexone.com/lesson/introduction...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #memory #ipython

#avk47



ACCEPTED ANSWER

Score 265


%reset seems to clear defined variables.




ANSWER 2

Score 72


EDITED after @ErdemKAYA comment.

To erase a variable, use the magic command:

%reset_selective <regular_expression>

The variables that are erased from the namespace are the one matching the given <regular_expression>.

Therefore

%reset_selective -f a 

will erase all the variables containing an a.

Instead, to erase only a and not aa:

In: a, aa = 1, 2
In: %reset_selective -f "^a$"
In: a  # raise NameError
In: aa  # returns 2

see as well %reset_selective? for more examples and https://regexone.com/ for a regex tutorial.

To erase all the variables in the namespace see:

%reset?



ANSWER 3

Score 67


In iPython you can remove a single variable like this:

del x



ANSWER 4

Score 17


Adding the following lines to a new script will clear all variables each time you rerun the script:

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

To make life easy, you can add them to your default template.

In Spyder: Tools>Preferences>Editor>Edit template