Reputation: 1967
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.
Upvotes: 1
Views: 197
Reputation: 9075
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.
Upvotes: 1