How to reload all imported modules?

14,173

Solution 1

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)

Solution 2

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).

Share:
14,173
user
Author by

user

Updated on June 22, 2022

Comments

  • user
    user almost 2 years

    I have several modules, I would like to reload without having to restart Sublime Text, while I am developing a Sublime Text package.

    I am running Sublime Text build 3142 which comes with python3.3 running continuously its packages/plugins. However while developing a plugin, I import a third part module I added to path as:

    import os
    import sys
    
    def assert_path(module):
        """
            Import a module from a relative path
            https://stackoverflow.com/questions/279237/import-a-module-from-a-relative-path
        """
        if module not in sys.path:
            sys.path.insert( 0, module )
    
    current_directory = os.path.dirname( os.path.realpath( __file__ ) )
    assert_path( os.path.join( current_directory, 'six' ) ) # https://github.com/benjaminp/six
    
    import six
    

    But when I edit the source code of the module six I need to close and open Sublime Text again, otherwise Sublime Text does not gets the changes to the six python module.


    Some code I have tried so far:

    print( sys.modules )
    import git_wrapper
    imp.reload( find_forks )
    imp.reload( git_wrapper )
    imp.reload( sys )
    
    1. Proper way to reload a python module from the console
    2. Reloading module giving NameError: name 'reload' is not defined