Importing a module, using a variable name?

Anthony J Wilkinson anthony at dstc.edu.au
Fri Mar 10 03:24:36 CET 2000


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

Try:

module_to_import = 'sys'
evalstr = 'import ' + module_to_import
exec(evalstr)


you will see the following:

>>> module_to_import = 'sys'
>>> evalstr = 'import ' + module_to_import
>>> dir()
['__builtins__', '__doc__', '__name__', 'evalstr', 'module_to_import']
>>> exec(evalstr)
>>> dir()
['__builtins__', '__doc__', '__name__', 'evalstr', 'module_to_import',
'sys']

Cheers,
Anthony
_____________________________________________________________________
Anthony J Wilkinson                                  anthony at dstc.com
Software Engineer                                     http://dstc.com
DSTC Pty Ltd                                     Ph:  +61 7 3365 4310






More information about the Python-list mailing list