How to reload a module's function in Python?

后端 未结 8 1791
遥遥无期
遥遥无期 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:38

    This one also works.

    • Pros: it supports from ... import ... instead of module.my_function, and it does not require to write the module as a string.
    • Cons: it needs the module to be imported.
    # Import of my_function and module
    import my_utils
    from my_utils import my_function
    
    # Test:
    my_function()
    
    # For reloading:
    from importlib import reload
    reload(my_utils)
    from my_utils import my_function
    
    # Test again:
    my_function()
    

提交回复
热议问题