1

I have this code that carry module manually

exec("import" + moduleName + " as selectedModule")
importlib.reload(selectedModule)

But this code make

name 'seletedModule' is not defined

It is not happened on python2.x. How to import this on python3?

JongHyeon Yeo
  • 879
  • 1
  • 10
  • 18

1 Answers1

4

If you need to import a library dynamically, don't use exec, its not safe.

Use importlib.import_module instead.

selected_module = importlib.import_module(module_name)
importlib.reload(selected_module)

As for the error you're getting: you're probably calling exec within a function scope, thus you'll need you manually set globals and locals to be the same in exec (Using a function defined in an exec'ed string in Python 3). Workaround:

exec("<do-stuff>", globals())
Taku
  • 31,927
  • 11
  • 74
  • 85