473,699 Members | 2,114 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 1926
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
1275
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
2190
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
6413
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
3761
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
1458
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
1257
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
3927
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
2734
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
9038
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...
1
8920
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8887
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...
1
6536
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5877
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
4378
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
4633
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3060
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2351
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.