Skip to content

Instantly share code, notes, and snippets.

@shwang
Created August 6, 2019 00:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shwang/09bd0ffef8ef65af817cf977ce4698b8 to your computer and use it in GitHub Desktop.
Save shwang/09bd0ffef8ef65af817cf977ce4698b8 to your computer and use it in GitHub Desktop.
from importlib import reload
from types import ModuleType
def rreload(module):
"""Recursively reload a module and all its submodules.
Graph DFS strategy modified from
https://stackoverflow.com/questions/15506971/recursive-version-of-reload
"""
visited = set()
def visit(m):
if m in visited:
return
visited.add(m)
reload(module)
for attribute_name in dir(m):
attribute = getattr(m, attribute_name)
if type(attribute) is ModuleType:
visit(attribute)
visit(module)
@dtasev
Copy link

dtasev commented Aug 7, 2019

Had to change line 14 from reload(module) to reload(m)

@iExalt
Copy link

iExalt commented May 24, 2020

Line 14 is in the wrong place, we want to visit (and reload) child nodes before reloading the current node.
Incorporating @dtasev's changes, this is the correct algorithm:

def rreload(module):
    """Recursively reload a module and all its submodules.
    Graph DFS strategy modified from
    https://stackoverflow.com/questions/15506971/recursive-version-of-reload
    """
    from types import ModuleType
    visited = set()

    def visit(m):
        if m in visited:
            return
        visited.add(m)
        for attribute_name in dir(m):
            attribute = getattr(m, attribute_name)
            if type(attribute) is ModuleType:
                visit(attribute)
        reload(m)
    visit(module)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment