How to reload a module's function in Python?

后端 未结 8 1798
遥遥无期
遥遥无期 2020-11-28 09:27

Following up on this question regarding reloading a module, how do I reload a specific function from a changed module?

pseudo-code:

from foo import b         


        
8条回答
  •  旧巷少年郎
    2020-11-28 09:35

    If you are the author of foo.py, you can write:

    with open('bar.py') as f: bar_code=compile(f.read(),'bar.py','exec')
    
    def bar(a,b):
        exec(bar_code)
    
    def reload_bar():
        global bar_code
        with open('bar.py') as f: bar_code=compile(f.read(),'bar.py','exec') 
    

    Then, in your pseudocode, reload if bar.py has changed. This approach is especially nice when bar lives in the same module as the code that wants to hot-reload it rather than the OP's case where it lives in a different module.

提交回复
热议问题