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

Steven Reddie smr at essemer.com.au
Mon Mar 7 01:40:25 EST 2005


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

That is, effectively expanding out to:

	def libinfo():
		__import__('libinfo.module1')
		module1.libinfo()
		CFLAGS+=module1.CFLAGS	

I think the m in "m.libinfo()" is a string and so there is a failure to find
a libinfo member of a string object (which makes sense).  Is there some way
to call the libinfo member of the object named by m?  Am I heading into
reflection territory?

Regards,

Steven

-----Original Message-----
From: Hye-Shik Chang [mailto:hyeshik at gmail.com] 
Sent: Monday, 7 March 2005 4:48 PM
To: Steven Reddie
Cc: python-list at python.org
Subject: Re: Possible to import a module whose name is contained in a
variable?

On 6 Mar 2005 21:34:08 -0800, Steven Reddie <smr at essemer.com.au> wrote:
> Hi,
> 
> I want to do something like the following, which doesn't work:
> 
>     modulename = 'module'
>     import modulename
> 
> The error is that there is no module named 'modulename'.  Is there a 
> way to get that variable expanded?
> 

modulename = 'module'
module = __import__(modulename)


Hye-Shik




More information about the Python-list mailing list