3

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)
Jamie
  • 7,075
  • 12
  • 56
  • 86
Antobat
  • 31
  • 7
  • For one reason, generally you want to avoid re-inventing the wheel. So I guess for the same reason you don't use `def my_print(x): sys.stdout.write(x+'\n')` – juanpa.arrivillaga Jun 10 '18 at 20:23
  • 1
    For one thing, it's easier to spot mistakes in your code when you use importlib... Did you notice that your `exec` code doesn't work? – Aran-Fey Jun 10 '18 at 20:28
  • Maybe you found this helpful: https://stackoverflow.com/questions/49012761/using-exec-to-load-module-variables-using-a-file-path – DecaK Jun 10 '18 at 20:37
  • @Aran-Fey Thanks for pointing that out. I'm gonna be quite honest, and admit that I kinda just made that code up for the example. It works in my original code and I have absolutely no intention of trying to find out why it does. Hopefully you still get the point I'm making. – Antobat Jun 10 '18 at 20:43

0 Answers0