Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reloading dependent modules in Python

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?

like image 358
rottentomato56 Avatar asked May 21 '13 16:05

rottentomato56


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.

like image 67
Aya Avatar answered Oct 05 '22 23:10

Aya


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.

like image 24
danodonovan Avatar answered Oct 06 '22 01:10

danodonovan