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 bar
if foo.py has changed:
reload bar
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 bar
if foo.py has changed:
reload bar
While reloading of functions is not a feature of the
reload
function, it is still possible. I would not recommend doing it in production, but here is how it works: The function you want to replace is a object somewhere in memory, and your code might hold many references to it (and not to the name of the function). But what that function actually does when called is not saved in that object, but in another object that, in turn, is referenced by the function object, in its attribute__code__
. So as long as you have a reference to the function, you can update its code:Module mymod:
Other module / python session:
Now, in case you do not have a reference to the old function (i.e. a
lambda
passed into another function), you can try to get a hold of it with thegc
module, by searching the list of all objects:You can't reload a method from a module but you can load the module again with a new name, say
foo2
and saybar = foo2.bar
to overwrite the current reference.Note that if
bar
has any dependencies on other things infoo
or any other side effects, you will get into trouble. So while it works, it only works for the most simple cases.As of today, the proper way of doing this is:
Tested on python 2.7, 3.5, 3.6.
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.
If you are the author of
foo.py
, you can write: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.You will have to use
reload
to reload the module, since you can't reload just the function: