Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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.
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)
–
–
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()
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))
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.