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

S

Steven Reddie

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?

Regards,

Steven
 
H

Hye-Shik Chang

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
 
S

Steven Bethard

Claudio said:
modulename = 'module'
cmd = 'import '+modulename
exec(cmd)

Check also the thread:
How do I import everything in a subdir?
in THIS newsgroup.

And note that it tells you to use __import__, not exec. =)

STeVe
 
C

Claudio Grondi

Steven Reddie said:
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?

Regards,

Steven

modulename = 'module'
cmd = 'import '+modulename
exec(cmd)

Check also the thread:
How do I import everything in a subdir?
in THIS newsgroup.

Claudio
P.S.
MODULES = [ 'module1', 'module2' ]

def libinfo():
for m in MODULES:
__import__('libinfo.'+m)
m.libinfo()
CFLAGS+=m.CFLAGS

indentation error?
 
H

Heiko Wundram

I try to avoid using any of the
__xxxx__() functions if possible
(considering this a good
programming style).

This is never good style, at least in the case of exec. exec is evil.

What works (beware that the below code is nevertheless untested and might
contain little warts) and is the "usual" and clean way to go:

### libinfo/__init__.py

# Empty.

### libinfo/Module1.py

def libinfo():
return "I am module1."

CFLAGS = ["-DMODULE1"]

### libinfo/Module2.py

def libinfo():
return "I am module2."

CFLAGS = ["-DMODULE2"]

### Importer.py

modules = {}
CFLAGS = []

def load_modules(to_load=["module1","module2"]):
global modules, CFLAGS

for mod in to_load:
try:
modules[mod] = getattr(__import__("libinfo.%s" % mod),mod)
except ImportError:
print "Could not load %s." % mod
continue
print "Module: %s (%r)." % (mod,modules[mod])
print "Modules libinfo: %r." % modules[mod].libinfo()
CFLAGS += modules[mod].CFLAGS

print "Total CFLAGS: %s." % CFLAGS

if __name__ == "__main__":
load_modules()
print "Module container: %s." % modules

### End Importer.py

HTH!

--
--- Heiko.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.0 (GNU/Linux)

iD8DBQBCLCgXf0bpgh6uVAMRAhCUAJ95kbz6bMWAV7j42hxrh1nYEvj4lgCfZoD3
p0E0cdgp4io2eyGfL6u2lho=
=wYq0
-----END PGP SIGNATURE-----
 
M

Michael Hoffman

Claudio said:
STeVe,

may I ask you for more details on this?
Any disadvantages while using exec()
in this context?

I try to avoid using any of the
__xxxx__() functions if possible
(considering this a good
programming style).

Avoiding exec (which is a statement, not a function) is much more
important. Since it executes arbitrary code, you can get unpredictable
results from it.
w00t

Consider the case where z = "shutil; shutil.rmtree('/')"
 
C

Claudio Grondi

STeVe,

may I ask you for more details on this?
Any disadvantages while using exec()
in this context?

I try to avoid using any of the
__xxxx__() functions if possible
(considering this a good
programming style).

Claudio
 
G

Gerrit Holl

Ed said:
Is there any way to use __import__ to replace the following:

exec("from %s import *" % modulename)

No.

Gerrit.

--
Weather in Twenthe, Netherlands 07/03 13:25:
4.0°C Few clouds mostly cloudy wind 5.4 m/s NW (57 m above NAP)
--
In the councils of government, we must guard against the acquisition of
unwarranted influence, whether sought or unsought, by the
military-industrial complex. The potential for the disastrous rise of
misplaced power exists and will persist.
-Dwight David Eisenhower, January 17, 1961
 
M

Michael Hoffman

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top