[Tutor] Passing a variable to 'import'

Rob McGee i812@iname.com
Wed, 19 Dec 2001 23:37:23 -0600

On Wed, Dec 19, 2001 at 11:26:01PM -0500, Chris Keelan wrote:
> >>moduleName="someModule"
> >>def import_module(someModule):
>         import someModule
> Of course that gives me the following output:
> >>Traceback (most recent call last):
> >>  File "<stdin>", line 1, in import_module
> >>ImportError: No module named someModule

Sounds like a job for my once-beloved "exec" statement. :)

moduleName = 'someModule'

def import_module(someModule):
  """Imports a module (someModule as string)"""
  exec 'import ' + someModule


But don't listen to me, I'm a beginner. :) IIRC there's also the
execfile() function which might do it more elegantly. See the
lib/built-in-funcs.html in your documentation (or online at

HTH, sorry if it doesn't :) ...
    Rob - /dev/rob0