1

I have a program like this:

if __name__=="__main__":
  foo = expensiveDataProcessClass(filepath)

  y = foo.doStuff()
  y = foo.doOtherStuff()

I'm testing things out as a I build it in ipython with the %run myprogram command.

After it's running, since it takes forever, I'll break it with ctrl+C and go rewrite some stuff in the file.

Even after I break it, though, IPython has foo stored.

>type(foo) 
__main__.expensiveDataProcessClass

I'm never having to edit anything in foo, so it would be cool if I could update my program to first check for the existence of this foo variable and just continue to use it in IPython rather than doing the whole creation process again.

1 Answer 1

1

You could first check for the variable's existence, and only assign to it if it doesn't exist. Example:

if __name__=="__main__":
    if not "foo" in globals()
        foo = expensiveDataProcessClass(filepath)

However, this won't actually work (in the sense of saving a foo assignment). If you read IPython's doc on the %run magic, it clearly states that the executed program is run in its own namespace, and only after program execution are its globals loaded into IPython's interactive namespace. Every time you use %run it will always not have foo defined from the program's prospective.

Sign up to request clarification or add additional context in comments.

3 Comments

So this would work in normal execution, just not with ipython's %run?
If you mean by doing python myscript.py then no, because python programs are always given a fresh execution environment. In fact %run is, from any program's prospective, exactly the same as executing it normally. The difference is the final program state is then loaded into IPython for you to examine. This is useful for debugging purposes to see what state things where in when it went wrong.
However, %run -i runs a script in your interactive namespace - so then this check would would work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.