reloading module which has been imported to another module

后端 未结 6 1045
难免孤独
难免孤独 2021-01-01 19:32

Let\'s face it, the whole business of reloading python code after changing it is a mess. I figured out awhile back that calling import at the in

6条回答
  •  轮回少年
    2021-01-01 20:02

    Ok, I'm not sure that qualifies as an answer without a change to the code, but... at least, that doesn't involve a change to module1.

    You can use some module wrapper class, that saves loaded modules before and after loading module1 and that provides a reload method, something like that:

    import sys
    
    class Reloader(object):
        def __init__(self, modulename):
            before = sys.modules.keys()
            __import__(modulename)
            after = sys.modules.keys()
            names = list(set(after) - set(before))
            self._toreload = [sys.modules[name] for name in names]
    
        def do_reload(self):
            for i in self._toreload:
                reload(i)
    

    Then load module1 with:

    reloader = Reloader('module1')
    

    Atfer that you can modify module2 and reload it in interpreter with:

    reloader.do_reload()
    

提交回复
热议问题