8

I want to use importlib to reload a module whose name is dynamically generated.

Example:

import sys

def some_func():
    return "sys"

want_reload = some_func()

Now how do I reload the module sys using the variable want_reload? I can't supply it directly to importlib.reload() because it says it expects a module, not str.

It would be better if an invalid string, or a module that's not loaded, is supplied, e.g. "........", that it raises an exception.

iBug
  • 35,554
  • 7
  • 89
  • 134

2 Answers2

12

importlib.import_module() won't reload, but returns a ref to the module even if already loaded:

import sys
import importlib

def some_func():
    return "sys"

want_reload = some_func()
want_reload_module = importlib.import_module(want_reload)
importlib.reload(want_reload_module)
spinkus
  • 7,694
  • 4
  • 38
  • 62
  • I want to avoid that, if a module is not loaded, don't load it. Right now it seems `importlib.import_module` will import the module if it's not loaded already. – iBug Sep 02 '18 at 07:05
  • Thanks for your answer that gave me a useful hint! – iBug Sep 02 '18 at 07:09
  • np. Hmm so you want to reload a module but only if it is loaded. That is not clear from your question. But anyway, loaded modules are listed in [sys,modules](https://stackoverflow.com/questions/30483246/how-to-check-if-a-python-module-has-been-imported#30483269) – spinkus Sep 02 '18 at 07:11
  • Yeah that's what I thought. See my own answer below that takes it exactly. – iBug Sep 02 '18 at 07:13
5

Hinted by @spinkus's answer, I came up with this solution:

Since I don't want to load a module if it's not loaded already, I can fetch the ref from sys.modules

want_reload = some_func()
try:
    want_reload_module = sys.modules[want_reload]
    importlib.reload(want_reload_module)
except KeyError:
    raise ImportError("Module {} not loaded. Can't reload".format(want_reload))
iBug
  • 35,554
  • 7
  • 89
  • 134
  • would be better to check if want_reload in sys.modules, instead of just using a try-except to catch the inevitable errors – mtsolmn Nov 06 '20 at 08:55
  • When attempting to reload a local module (relative import) I get "ModuleNotFoundError: spec not found for the module 'block'" is there any way to create this spec or avoid this error? – ChildishGiant Feb 02 '21 at 23:11