In Python, if you want to dynamically import a module (such as from a string name) you can use the module importlib
and the function importlib.import_module("foo")
, which essentially gives the same result as import foo
(but it's dynamic).
Anyway, in my program, I'm using a function to import a module from a list, so it looks something like this:
# Note: this code does not produce the desired result.
# Please see the snippet below, for the working version
module_list = ["os"]
def import_module(name):
exec("global {}".format(name))
exec("import {}".format(name))
for item in module_list:
import_module(item)
I haven't seen this type of solution anywhere else on the web. What I'm asking, is why? Is it bad practice because I'm using the exec()
function (as I've read not to do countless times) or is it because It's simply more confusing
Edit: I feel like it's relevant to note that it's not my exact code above, but it's the part that's actually relevant to this question, instead of confusing people
Edit (2): thanks to user Aran-Fey for discovering that my code doesn't work. I hadn't properly tested this specific snippet. Here's a version that works in python 3.6:
module_list = ["os"]
def import_module(name):
exec("global {}".format(name), globals())
exec("import {}".format(name), globals())
for item in module_list:
import_module(item)