Reloading dependent modules in Python

Let's say I have a Python script main.py that imports othermodule.py . Is it possible to write reload(othermodule) in main.py so that when I make changes to othermodule.py , I can still just reload(main) , which then reloads another module?

+4
source share
2 answers

Well, it's not quite that simple. Assuming you have main.py like this ...

 import time import othermodule foo = othermodule.Foo() while 1: foo.foo() time.sleep(5) reload(othermodule) 

... and a 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 working, it will continue to print foo , not bar , because the foo instance in main.py will continue to use the old class definition, although you can avoid this by doing main.py as follows:

 import time import othermodule while 1: foo = othermodule.Foo() foo.foo() time.sleep(5) reload(othermodule) 

Point, you need to know about the types of changes for imported modules that will cause problems with reload() .

It may help to include part of the source code in the source question, but in most cases it is probably safe only to restart the entire script.

+3
source

Python already has reload() , isn't that good enough?

From your comments, it sounds like you might be interested in the deep reload function in ipython , although I would use it with caution.

+1
source

Source: https://habr.com/ru/post/1481998/


All Articles