473,405 Members | 2,261 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

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

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
Jul 18 '05 #1
10 1894
On 6 Mar 2005 21:34:08 -0800, Steven Reddie <sm*@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
Jul 18 '05 #2
"Steven Reddie" <sm*@essemer.com.au> schrieb im Newsbeitrag
news:f9**************************@posting.google.c om...
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?

Jul 18 '05 #3
Claudio Grondi wrote:
"Steven Reddie" <sm*@essemer.com.au> schrieb im Newsbeitrag
news:f9**************************@posting.google.c om...

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'
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
Jul 18 '05 #4
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

"Steven Bethard" <st************@gmail.com> schrieb im Newsbeitrag
news:Nf********************@comcast.com...
Claudio Grondi wrote:
"Steven Reddie" <sm*@essemer.com.au> schrieb im Newsbeitrag
news:f9**************************@posting.google.c om...

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'
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

Jul 18 '05 #5
On Monday 07 March 2005 11:52, Claudio Grondi wrote:
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)

iD8DBQBCLCgXf0bpgh6uVAMRAhCUAJ95kbz6bMWAV7j42hxrh1 nYEvj4lgCfZoD3
p0E0cdgp4io2eyGfL6u2lho=
=wYq0
-----END PGP SIGNATURE-----

Jul 18 '05 #6
Claudio Grondi wrote:
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.
z = "sys; print 'w00t'"
exec "import " + z

w00t

Consider the case where z = "shutil; shutil.rmtree('/')"
--
Michael Hoffman
Jul 18 '05 #7
On Mar 7, 2005, at 5:23 AM, Michael Hoffman wrote:
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.


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

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

___/
/
__/
/
____/
Ed Leafe
http://leafe.com/
http://dabodev.com/
Come to PyCon!!!! http://www.python.org/pycon/2005/

Jul 18 '05 #8
Ed Leafe wrote:
On Mar 7, 2005, at 5:23 AM, Michael Hoffman wrote:
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.


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
Jul 18 '05 #9
Gerrit Holl wrote:
Ed Leafe wrote:
On Mar 7, 2005, at 5:23 AM, Michael Hoffman wrote:
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.
Is there any way to use __import__ to replace the following:

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

No.


Between the following two recipes, it seems unlikely that a simple
"No" is really correct:

http://aspn.activestate.com/ASPN/Coo.../Recipe/223972

http://aspn.activestate.com/ASPN/Coo.../Recipe/307772

A variation on some of the code therein should certainly be
able to do the equivalent of "from xx import *". (The addition
of support for __all__ is at least required for full emulation.)

-Peter
Jul 18 '05 #10
Ed Leafe wrote:

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

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


I shouldn't do this but:

module = __import__(modulename)
try:
for key in module.__all__:
globals()[key] = module[key]
except AttributeError:
globals().update(module.__dict__)

But really, you shouldn't be using from x import * as it
has unpredictable results as well.

http://www.python.org/doc/faq/progra...rt-in-a-module
--
Michael Hoffman
Jul 18 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Remy C. Cool | last post by:
Hello, A couple of months ago, I posted a question related to the same problem, but didn't get any replies. I've created a ugly workaround but still would like to get some insight on the matter....
4
by: MackS | last post by:
Hi I'm new to Python, I've read the FAQ but still can't get the following simple example working: # file main_mod.py: global_string = 'abc' def main():
23
by: Shane Hathaway | last post by:
Here's a heretical idea. I'd like a way to import modules at the point where I need the functionality, rather than remember to import ahead of time. This might eliminate a step in my coding...
10
by: Ben Finney | last post by:
Howdy all, Question: I have Python modules named without '.py' as the extension, and I'd like to be able to import them. How can I do that? Background: On Unix, I write programs intended to...
9
by: fegge | last post by:
i have written script save as hello.py. i can run it. but why cant i import it as a modular in other programs?
0
by: Anders J. Munch | last post by:
Now 2.5 is out, and we have a syntax for explicit relative imports (PEP 328, http://www.python.org/dev/peps/pep-0328/, in case anyone wasn't paying attention). The long-term plan is that the...
3
by: Steven W. Orr | last post by:
This is all an intro learning experience for me, so please feel free to explain why what I'm trying to do is not a good idea. In the Cookbook, they have a recipe for how to create global...
49
by: Martin Unsal | last post by:
I'm using Python for what is becoming a sizeable project and I'm already running into problems organizing code and importing packages. I feel like the Python package system, in particular the...
12
by: Alan Isaac | last post by:
Are relative imports broken in 2.5? Directory ``temp`` contains:: __init__.py test1.py test2.py File contents: __init__.py and test2.py are empty test1.py contains a single line::
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.