I have two .py
scripts. script1.py
and script2.py
I am importing few variables from script2.py
like:
from script2 import variable1 as var1
which works fine.
But when I update variable1
in script2.py
, and then re-run script1.py
, the update of variable1
doesn't show up in script1.py
. Why is that so?
The update of variable1
shows up if I close IPython completely and then re-open IPython again. But I don't want to do this all the time as I need few plot's to be open.
I am using IPython 1.2.1
and Python 2.7.6
(if further info maybe needed).
It would be easier just to store the value in a file. For example, in the first script you would have:
and in the second script you would have:
For ipython, use the
%load
magic command:If you have to change the variables often I think its not a good approach to write it to a python script but rather to a config file. There you could simple read it like this
While the variable is written in your
config.cfg
file like this:You could also save it as JSON and just use a json reader instead of the config reader.
In the end you can get your variable with
getVar('var1')
and it will always be up to date.There is a way to reload modules, though it doesn't seem to work well with aliasing. You can use
reload(module_name)
. As you'll see the docs note that your aliases wont be refreshed:It instead suggests using
You could still alias, but you'd need to refresh the aliased names each time:
If you didn't do this,
var1
would hold the old value.You could however have a quick function to do this all at once if you think it's necessary (and if it is happening often)
Note I use
global
here so thatvar1
is modified in the global namespace, not just declared in that function. If you really only have one value you could usereturn var1
, but I think this is a rare case whereglobal
is better.