How to reload a module's function in Python?

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

    What you want is possible, but requires reloading two things... first reload(foo), but then you also have to reload(baz) (assuming baz is the name of the module containing the from foo import bar statement).

    As to why... When foo is first loaded, a foo object is created, containing a bar object. When you import bar into the baz module, it stores a reference to bar. When reload(foo) is called, the foo object is blanked, and the module re-executed. This means all foo references are still valid, but a new bar object has been created... so all references that have been imported somewhere are still references to the old bar object. By reloading baz, you cause it to reimport the new bar.


    Alternately, you can just do import foo in your module, and always call foo.bar(). That way whenever you reload(foo), you'll get the newest bar reference.

    NOTE: As of Python 3, the reload function needs to be imported first, via from importlib import reload

    0 讨论(0)
  • 2020-11-28 09:58

    Hot reloading is not something you can do in Python reliably without blowing up your head. You literally cannot support reloading without writing code special ways, and trying to write and maintain code that supports reloading with any sanity requires extreme discipline and is too confusing to be worth the effort. Testing such code is no easy task either.

    The solution is to completely restart the Python process when code has changed. It is possible to do this seamlessly, but how depends on your specific problem domain.

    0 讨论(0)
提交回复
热议问题