473,748 Members | 9,596 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 1933
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
1279
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
2195
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
6418
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
3769
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
1462
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
3937
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
2738
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
8991
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
8830
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9541
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8242
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...
1
6796
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
6074
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
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3312
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
3
2215
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.