How to reload all imported modules?
To list all imported modules, you can use sys.modules.values()
.
import sys
sys.modules.values()
sys.modules
is a dictionary that maps the string names of modules to their references.
To reload modules, you can loop over the returned list from above and call importlib.reload
on each one:
import importlib
for module in sys.modules.values():
importlib.reload(module)
I imagine in most situations, you want to reload only the modules that you yourself are editing. One reason to do this is to avoid expensive reloads, and another is hinted in @dwanderson's comment, when reloading pre-loaded modules might be sensitive to the order in which they are loaded. It's particularly problematic to reload importlib
itself. Anyways, the following code reloads only the modules imported after the code is run:
PRELOADED_MODULES = set()
def init() :
# local imports to keep things neat
from sys import modules
import importlib
global PRELOADED_MODULES
# sys and importlib are ignored here too
PRELOADED_MODULES = set(modules.values())
def reload() :
from sys import modules
import importlib
for module in set(modules.values()) - PRELOADED_MODULES :
try :
importlib.reload(module)
except :
# there are some problems that are swept under the rug here
pass
init()
The code is not exactly correct because of the except
block, but it seems robust enough for my own purposes (reloading imports in a REPL).