Importing a module, using a variable name?
Just van Rossum
just at letterror.com
Fri Mar 10 13:36:28 CET 2000
Anthony J Wilkinson wrote:
> On Fri, 10 Mar 2000, Benjamin Schollnick wrote:
> > Is it possible to import a module, via a variable? I've tried it
> > module_to_import = "test"
> > import module_to_import
> module_to_import = 'sys'
> evalstr = 'import ' + module_to_import
In my opinion, the following idiom is nicer:
a_module = __import__("sys")
It's not quite the same, since it doesn't the module won't become
visible as "sys" but as "a_module", but in my experience that's usually
no problem (often it's even preferable) when you're importing modules
Minor nit: exec is a statement, therefore you can (and should) write
More information about the Python-list