importing module through variable

Al-Amerrho H. Amerin al_amerin at yahoo.com
Wed Jun 14 00:17:40 EDT 2000


"André Dahlqvist" wrote:

> Hi
>
> I have a variable which is assigned the name of a module. Is it possible
> to use this variable in an import statement? Someone told me I could use
> "exec("import %s" %var) and while this works I am not sure how I can
> access the module by it's name after that. Using something like
> var.modfunc() won't do it since 'var' is just a string containing the
> modules name.
>
> // André

If you want access to the module instance that you've imported,  you can do
this:

exec('import %s' % var)
var  =  sys.modules[var]

You can now say:

var.modfunc()

Hope this works for you.


Al-




More information about the Python-list mailing list