getting modules optionally

Ype Kingma ykingma at accessforall.nl
Wed Nov 21 15:21:50 EST 2001


Steve Holden wrote:
> 
> "Giorgi Lekishvili" <gleki at gol.ge> wrote in message
> news:3BFC2647.D9692B49 at gol.ge...
> > Dear all!
> >
> > I apologize for this nebye-like question.
> >
> > Suppose, we have a package with one __init__.py file, while the rest are
> > other modules (let's call them active modules), which do the essential
> > stuff.
> >
> > Apparently, I need to start like this:
> >
> >
> >      from MyPackage import *
> >
> > I need to import only one active module. This can be done by hardcoding:
> >
> >      from MyPackage.ThisModule import *
> >
> > 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?
> >
> >      from MyPackage.modname import *
> >
> Take a look at the built-in __import__() function.

You might also consider avoiding 'from .. import *'.
It's ok for interactive use, but it might unexpectedly override some
names that are already the module namespace.

It is better to specify a new prefix name for the imported names:

import MyPackage.modname as Mymodname

  or

from MyPackage import modname

  or

from MyPackage import modname as MyModname


Regards,
Ype



More information about the Python-list mailing list