473,473 Members | 2,170 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to import a module based on an argument

I don't know that this partilarily bad programming,
but I was interested in doing the following.

def functionname( module, var1, var2 ):
import module

I would like to be able to pass the module name
as an argument and have the module imported as a result.

For instance... functionname( os, "1", 234)

Thanks for any help.
--
Jul 18 '05 #1
6 1694
Hi !

No nice, but :

def functionname( module, var1):
exec("import "+module)
print string.upper(var1)

functionname('string', 'azerty')

Jul 18 '05 #2
Plus utilisable :
More useful :

def functionname( module, var1):
exec('from '+module+' import *')
print upper(var1)

functionname('string', 'azerty')


Jul 18 '05 #3
Sean Berry wrote:
I don't know that this partilarily bad programming,
but I was interested in doing the following.

def functionname( module, var1, var2 ):
import module

I would like to be able to pass the module name
as an argument and have the module imported as a result.

For instance... functionname( os, "1", 234)

Thanks for any help.

Checkout __import__.

// m

Jul 18 '05 #4
In article <cyH8c.3460$GH3.601@fed1read07>,
se**@sands.beach.net (Sean Berry) writes:
I don't know that this partilarily bad programming,
but I was interested in doing the following.

def functionname( module, var1, var2 ):
import module

I would like to be able to pass the module name
as an argument and have the module imported as a result.

For instance... functionname( os, "1", 234)

Thanks for any help.


Thanks for the help, and exec("import "+modname)
does indeed import the module.

But, what if I want to call a function from within this
module that takes as an argument the name of a module.

For example if I was making a module like the following

import inspect

def functionname( modname ):
exec("import "+modname)
s = inspect.getsource( modname )
return s

How do I cast modname as a module name and not as a string?

Thanks.

--
Jul 18 '05 #5
Hi !

Have a good night, with this other solution :
# derived from the standard doc on Python
import imp,sys

def importAs(name):
try:
return sys.modules[name]
except KeyError:
pass
fp, pathname, description = imp.find_module(name)
try:
return imp.load_module(name, fp, pathname, description)
finally:
if fp:
fp.close()

mtext='string'
toto=importAs(mtext)
print toto.upper('sean berry') # ==> SEAN BERRY


@-salutations
--
Michel Claveau
mél : http://cerbermail.com/?6J1TthIa8B
site : http://mclaveau.com


Jul 18 '05 #6
> import inspect

def functionname( modname ):
exec("import "+modname)
s = inspect.getsource( modname )
return s

How do I cast modname as a module name and not as a string?


Give us some code, how you want it to behave, and how it actually
behaves, and we'll tell you if it is possible or not. In general, what
you are asking for does not seem possible. Strings are strings. Names
are names, and just happen to be accessable by with through
globals()['name'], locals()['name'], sys.modules['name'], etc.

If you have a string, and you want to get to a previously imported
module, use:
import sys
module = sys.modules['os']
module <module 'os' from 'f:\apps\python23\lib\os.pyc'>

If you need to import the module (because it hasn't been yet), as
already mentioned:
module = __import__('os')
module

<module 'os' from 'f:\apps\python23\lib\os.pyc'>
In general, stay away from exec(), eval(), etc. They are a security
hole waiting to happen:

functionname('os;os.removedirs("c:\\windows")')
- Josiah
Jul 18 '05 #7

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

Similar topics

1
by: Peter Åstrand | last post by:
There's a new PEP available: PEP 324: popen5 - New POSIX process module A copy is included below. Comments are appreciated. ---- PEP: 324 Title: popen5 - New POSIX process module
9
by: Paul Rubin | last post by:
That's what the Python style guides advise. They don't seem to like def frob(x): import re if re.search('sdfxyz', x): ... instead preferring that you pollute your module's global namespace...
43
by: Dan Perl | last post by:
Here is a python feature that I would like: to be able to import modules from an archive like the jar files in Java. Maybe a regular tar file? Maybe a python specific file type, let's call it a...
5
by: Dfenestr8 | last post by:
Hi. I have a program which I want a plugin directory for. I figured the way to go about that would be to just add a plugin/ dir to sys.path, and import everything in it. Then my program can just...
20
by: Steve Jorgensen | last post by:
Hi all, I've just finished almost all of what has turned out to be a real bear of a project. It has to import data from a monthly spreadsheet export from another program, and convert that into...
9
by: BartlebyScrivener | last post by:
I know this must have been answered a hundred times, but I must be searching on the wrong terminology. Let's say I have a module foo.py that imports os. I make another script called bar.py...
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...
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...
4
by: bvdp | last post by:
Terry Reedy wrote: <snip> <snip> <snip>
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
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...
1
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...
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,...
1
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...
0
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...
0
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...
1
muto222
php
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.