Possible to import a module whose name is contained in avariable?

Scott David Daniels Scott.Daniels at Acm.Org
Mon Mar 7 18:32:20 EST 2005


Steven Reddie wrote:
> Hi,
> 
> Thanks, that seems to be what I was missing.  I'm having some further
> related trouble though.  I want to do something like this:
> 
> 	MODULES = [ 'module1', 'module2' ]
> 
> 	def libinfo():
> 		for m in MODULES:
> 			__import__('libinfo.'+m)
> 			m.libinfo()
> 			CFLAGS+=m.CFLAGS

Here's what you are missing:
     __import__ is a _function_ that returns a _module_ (which you are
     ignoring in the code above).

A better implementation is:
     def libinfo():
         for modulename in MODULES:
             module = __import__('libinfo.' + modulename)
             module.libinfo()
             CFLAGS += module.CFLAGS

The module returned by __import__ is _not_ recorded in sys.modules, so
if you have a chance of getting to modules more than once, you might
think about recording it there.  Otherwise, you will wind up in the
confusing state of having two of the "same" modules in your address
space.

So, an even better implementation might be:
     import sys

     def libinfo():
         for modulename in MODULES:
             fullname = 'libinfo.' + modulename
             module = __import__(fullname)
             sys.modules[fullname] = module
             module.libinfo()
             CFLAGS += module.CFLAGS


Remember, this is computer science, not mathematics.  We are allowed to
use more than a single (possibly strangely drawn) character per name.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list