JongHyeon Yeo
JongHyeon Yeo

Reputation: 1029

Python3 dynamic import with exec - why does 'as' not be executed?

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?

Upvotes: 1

Views: 118

Answers (1)

Taku
Taku

Reputation: 33724

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())

Upvotes: 4

Related Questions