Search code examples
pythonpython-3.xpython-importlib

Using importlib for cases like from x import *


How do I use importlib for dynamically reloading modules earlier imported as:

from my_module import *
import some_module as sm

The documentation gives example for plain imports like:

import my_module

as

importlib.reload('my_module')

version: Python 3.4


Solution

  • from my_module import * creates references to all names in my_module not starting with an underscore, or, if present, all names in the my_module.__all__ sequence.

    You'll have to re-create that same rebinding after a importlib.reload() call:

    def reload_imported_names(module_name, globals, *names):
        """Reload module and rebind imported names.
    
        If no names are given, rebind all names exported by the module
    
        """
        importlib.reload(module_name)
        module = sys.modules[module_name]
        if not names:
            names = getattr(module, '__all__', 
                            (n for n in dir(module) if n[0] != '_'))
        for name in names:
            globals[name] = getattr(module, name)
    

    where globals should be a reference to the globals of the module where you used from module_name import *. Within that module itself you can use the globals() function to access that dictionary.

    The function support both the from my_module import * case, and the from my_module import foo, bar cases:

    reload_imported_names('my_module', globals())  # import *
    reload_imported_names('my_module', globals(), 'foo', 'bar')  # import foo, bar