473,846 Members | 1,866 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1945
On 6 Mar 2005 21:34:08 -0800, Steven Reddie <sm*@essemer.co m.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__(modu lename)
Hye-Shik
Jul 18 '05 #2
"Steven Reddie" <sm*@essemer.co m.au> schrieb im Newsbeitrag
news:f9******** *************** ***@posting.goo gle.com...
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__('lib info.'+m)
m.libinfo()
CFLAGS+=m.CFLAG S


indentation error?

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

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******** ************@co mcast.com...
Claudio Grondi wrote:
"Steven Reddie" <sm*@essemer.co m.au> schrieb im Newsbeitrag
news:f9******** *************** ***@posting.goo gle.com...

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","modu le2"]):
global modules, CFLAGS

for mod in to_load:
try:
modules[mod] = getattr(__impor t__("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)

iD8DBQBCLCgXf0b pgh6uVAMRAhCUAJ 95kbz6bMWAV7j42 hxrh1nYEvj4lgCf ZoD3
p0E0cdgp4io2eyG fL6u2lho=
=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

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

Similar topics

0
1282
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. Case: XMLRPC client imports modules and packages from a XMLRPC server.
4
2200
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
6431
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 process. Currently, my process is I change code and later scan my changes to make matching changes to the import statements. The scan step is error prone and time consuming. By importing inline, I'd be able to change code without the extra scan...
10
3785
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 be run as commands to a file with no extension. This allows other programs to use the command as an interface, and I can re-write the program in some other language
9
382
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
1472
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 classical import syntax becomes absolute import only, so that all imports are explicitly one or the other. You can only use relative import from within packages. Trying to import a top-level module relatively from within same directory, produces...
3
1265
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 constants. ----------------- class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if self.__dict__.has_key(name):
49
3956
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 isomorphism between filesystem and namespace, doesn't seem very well suited for big projects. However, I might not really understand the Pythonic way. I'm not sure if I have a specific question here, just a general plea for advice. 1) Namespace....
12
2752
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
9879
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10640
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10330
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9477
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7050
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5714
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5906
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4111
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.