I've been trying to figure out exactly how IPython interacts with variables defined in code ran with %run. My understanding of %run is that it runs a given python file and then imports all of its data into the namespace of the current IPython notebook. However, I have been running into the following issue which I am unsure of how to explain given that description.
Say we have the following simple program named "foo.py".
foo = 5
def printVar():
print foo
def changeVar():
global foo
foo = foo + 1
If we run "foo.py" and ask IPython for the value of foo
we get the following.
In [1]: %run "foo.py"
In [2]: foo
Out[2]: 5
If we run changeVar()
and then ask IPython for the value of foo
again I would expect IPython to return 6
, but in fact, we get the following.
In[3]: changeVar()
In[4]: foo
Out[4]: 5
However, when we run printVar()
we get.
In[5]: printVar()
6
So what is going on here? On the surface it seems like we have reached a contradiction. I have been wondering if this is an issue analogous to variable scope. Local variables can have the same name as global variables but have different values, so is something similar going on here? If that's true, it seems that IPython doesn't update it's version of foo
when changeVal()
is ran.
I am running Python 2.7.13 in Enthought Canopy
Anyway, hopefully I am just missing something simple here. Thanks!
Yes, Ipython has its own namespace. Try using the %run -i
option. For more about this, type %run?
. Also, this article might be helpful:
https://support.enthought.com/hc/en-us/articles/204469630-Modules-are-already-available-in-Canopy-s-Python-PyLab-prompt-but-not-in-a-script