When I'm developing Python code, I usually test it in an ad-hoc way in the interpreter. I'll import some_module
, test it, find a bug, fix the bug and save, and then use the built-in reload
function to reload(some_module)
and test again.
However, suppose that in some_module
I have import some_other_module
, and while testing some_module
I discover a bug in some_other_module
and fix it. Now calling reload(some_module)
won't recursively re-import some_other_module
. I have to either manually reimport the dependency (by doing something like reload(some_module.some_other_module)
, or import some_other_module; reload(some_other_module)
, or, if I've changed a whole bunch of dependencies and lost track of what I need to reload, I need to restart the entire interpreter.
What'd be more convenient is if there were some recursive_reload
function, and I could just do recursive_reload(some_module)
and have Python not only reload some_module
, but also recursively reload every module that some_module
imports (and every module that each of those modules imports, and so on) so that I could be sure that I wasn't using an old version of any of the other modules upon which some_module
depends.
I don't think there's anything built in to Python that behaves like the recursive_reload
function I describe here, but is there an easy way to hack such a thing together?
I've run up against the same issue, and you inspired me to actually solve the problem.
from types import ModuleType try: from importlib import reload # Python 3.4+ except ImportError: # Needed for Python 3.0-3.3; harmless in Python 2.7 where imp.reload is just an # alias for the builtin reload. from imp import reload def rreload(module): """Recursively reload modules.""" reload(module) for attribute_name in dir(module): attribute = getattr(module, attribute_name) if type(attribute) is ModuleType: rreload(attribute)
Or, if you are using IPython, just use dreload
or pass --deep-reload
on startup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With