getting modules optionally

Hans Nowak wurmy at earthlink.net
Wed Nov 21 19:46:29 EST 2001


Giorgi Lekishvili wrote:

> What I can not do is to import the module, if I have its name as
> string.
> 
>      modname='ThisModule'
> 
> Of course, the code below doesn't work:
> 
>      from MyPackage.modname import *
> 
> The question: is there something like eval function, which could
> transfer the string as the real module name? In other words, how have
> I to treat the modname to make this code running?

Well, you can use exec:

  exec "from MyPackage.%s import *" % (modname)

Since "from .. import *" is usually not recommended, you might want to
use __import__:

  modname = __import__("MyPackage."+modname)

HTH,



More information about the Python-list mailing list