Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importlib.reload module from string?

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.

like image 416
iBug Avatar asked Sep 02 '18 06:09

iBug


People also ask

How do you reload a module?

How to Reload a Module. The reload() method is used to reload a module. The argument passed to the reload() must be a module object which is successfully imported before.

What is Importlib reload?

When reload() is executed: Python module's code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module's dictionary by reusing the loader which originally loaded the module.

How do you reload a module in Jupyter notebook?

Simple solution: Use the autoreload to make sure the latest version of the module is used. The autoreloading module is not enabled by default. So you have to load it as an extension. And each time you execute some code, IPython will reimport all the modules to make sure that you are using the latest possible versions.

How do you reload a function in Python?

You can't reload a method from a module but you can load the module again with a new name, say foo2 and say bar = foo2. bar to overwrite the current reference.


Video Answer


2 Answers

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)
like image 119
spinkus Avatar answered Nov 10 '22 08:11

spinkus


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))
like image 22
iBug Avatar answered Nov 10 '22 08:11

iBug