Search code examples
pythonreloadpython-module

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?


Solution

  • 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.