In Python you can reload a module as follows...
import foobar
import importlib
importlib.reload(foobar)
This works for .py
files, but for Python packages it will only reload the package and not any of the nested sub-modules.
With a package:
foobar/__init__.py
foobar/spam.py
foobar/eggs.py
Python Script:
import foobar
# assume `spam/__init__.py` is importing `.spam`
# so we dont need an explicit import.
print(foobar.spam) # ok
import importlib
importlib.reload(foobar)
# foobar.spam WONT be reloaded.
Not to suggest this is a bug, but there are times its useful to reload a package and all its submodules. (If you want to edit a module while a script runs for example).
What are some good ways to recursively reload a package in Python?
Notes:
For the purpose of this question assume the latest Python3.x
(currently using
importlib
)- Allowing that this may requre some edits to the modules themselves.
- Assume that wildcard imports aren't used (
from foobar import *
), since they may complicate reload logic.
IPython.lib.deepreload
module for recursive reloading. The code can be found here. Interestingly, the module is 285 sloc. – jme