Cannot import a module from a variable

Duncan Booth duncan.booth at invalid.invalid
Tue Oct 17 13:10:05 CEST 2006

"Tim Williams" <tim at> wrote:

>> The import statement expects a name (a symbol), not a string.
> eval( 'import %s' % modname)
> and
> eval( 'reload(%s)' % modname)
> Usual warnings about eval apply,  but in this case it is usable.

Did you actually try your suggestion before posting?

>>> modname = 'os'
>>> eval( 'import %s' % modname)

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    eval( 'import %s' % modname)
  File "<string>", line 1
    import os
SyntaxError: invalid syntax

Also, it is pretty pointless to import the module and not know which 
arbitrary variable name it will have created. It is much simpler just to 
use the __import__ builtin:

>>> module = __import__(modname)
>>> module
<module 'os' from 'C:\Python25\lib\os.pyc'>

More information about the Python-list mailing list