Let's say I have a Python script main.py that imports othermodule.py. Is it possible to write a reload(othermodule) in main.py so that when I make changes to othermodule.py, I can still just reload(main), which will then reload othermodule?
2 Answers
Well, it's not quite that simple. Assuming you have a main.py like this...
import time
import othermodule
foo = othermodule.Foo()
while 1:
foo.foo()
time.sleep(5)
reload(othermodule)
...and an othermodule.py like this...
class Foo(object):
def foo(self):
print 'foo'
...then if you change othermodule.py to this...
class Foo(object):
def foo(self):
print 'bar'
...while main.py is still running, it'll continue to print foo, rather than bar, because the foo instance in main.py will continue to use the old class definition, although you can avoid this by making main.py like this...
import time
import othermodule
while 1:
foo = othermodule.Foo()
foo.foo()
time.sleep(5)
reload(othermodule)
Point is, you need to be aware of the sorts of changes to imported modules which will cause problems upon a reload().
Might help to include some of your source code in the original question, but in most cases, it's probably safest just to restart the entire script.
3 Comments
reload(othermodule) in that last snippet you have. So if I reload(main) in the interpreter after changing othermodule.py, would it also reload(othermodule) and commit the changes?main.py. Assuming the first two lines are import othermodule and reload(othermodule), then reload(main) should work, but there may be complications, depending on what the actual code is.Python already has reload() is that not good enough?
From your comments, it sounds as if you might be interested in the deep reload function in ipython though I would use it with caution.
3 Comments
reload simply "destroys" the module object in sys.modules and then re-imports it. If this module imports some other module, this second module is not re-imported since it is already present in sys.module.
reloading the main file is a really big mistake...reload(main)(which @Bakuriu rightly says is a bad idea), that wouldn'treload(othermodule)by default. What are you trying to achieve here? Auto-reloading of any changed modules?