Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ipython run without destroying global variables defined in the target file

Tags:

python

ipython

I want to define some globals in some number crunching work I am doing, I am incrementally writing the script and don't want previous result to keep being loaded/recalculated. One approach is to split out mature code into a separate file and only python run interactively new code. However I just want to do it in a single file for speed of development.

I was under the assumption that a global defined in a file would persist between invocations of run, but they do not.

So my script has the following chunk if code :

if globals().has_key('all_post_freq') != True:
    print "creating all post freq var"
    global all_post_freq
    all_post_freq = all_post_freq_("pickle/all_post_freq.pickle")

How do I retain all_post_freq between invocations of ipython run

edit

ok I have split stuff up into files, but I know there must be a way of doing what I need to do :D

like image 537
Hassan Syed Avatar asked Nov 07 '13 12:11

Hassan Syed


1 Answers

When you %run a file, it is normally started in a blank namespace, and its globals are added to the interactive namespace when it finishes. There's a -i flag which will run it directly in the interactive namespace, so it will see variables you've already defined:

%run -i myscript.py
like image 185
Thomas K Avatar answered Sep 24 '22 04:09

Thomas K