473,560 Members | 2,985 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do i cast a string to be used as a module?

In article <cyH8c.3460$GH3 .601@fed1read07 >,
se**@sands.beac h.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.getsour ce( modname )
return s

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

Thanks.
Jul 18 '05 #1
3 1438
"sean" <se********@cox .net> schrieb im Newsbeitrag
news:9kM8c.4638 8$Bg.39277@fed1 read03...
In article <cyH8c.3460$GH3 .601@fed1read07 >,
se**@sands.beac h.net (Sean Berry) writes:
I don't know that this partilarily bad programming,
but I was interested in doing the following.

<snipped for brevity>

Does this help?:

http://groups.google.com/groups?q=vi...home.nl&rnum=1

Regards

Vincent Wehren
Jul 18 '05 #2
sean a écrit :
In article <cyH8c.3460$GH3 .601@fed1read07 >,
se**@sands.beac h.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.getsour ce( modname )
return s

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

Thanks.


exec("import chunk")
globals()["chunk"] <module 'chunk' from 'chunk.pyc'>

or even simplier :
__import__("chu nk")

<module 'chunk' from 'chunk.pyc'>
Yermat

Jul 18 '05 #3
"sean" <se********@cox .net> wrote in message news:<9kM8c.463 88$Bg.39277@fed 1read03>...

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.getsour ce( modname )
return s


Use s = inspect.getsour ce(sys.modules[modname]), of course, import sys
first.

Another thing that people often ask is how to access module level
variables by name string. The device there is the globals()
dictionary. So, remember that there are a few interesting namespace
dictionaries that come in handy:

(a) __builtin__ (it's a module, but you can access its namespace via
__builtin__.__d ict__)
(b) globals() and locals()
(c) sys.modules
(d) os.environ
etc.

One has to be careful with the locals() dictionary (use it only as
read-only.)

regards,

Hung Jung
Jul 18 '05 #4

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

Similar topics

18
5932
by: Graham Nicholls | last post by:
Hi. I'm having some fun with numbers. I've extraced an image sizes from a jpeg file img_x,img_y=image.getsize() then I'm trying to use those sizes to scale the image, but because python has decided that they are integers, I keep getting division by zero errors
0
1433
by: raca | last post by:
I am trying to create a generic SOA ServiceInvoker that will accept an XML string that will be used to deserialize an object generated by XSDObjectGen. The hierarchy goes like this: Requests...Request (1..n)... Payload (1)... PayloadCollection (1) ... Payload (0...n) I have the knowledge about the root object Responses which I can create...
17
2664
by: Hazz | last post by:
In this sample code of ownerdraw drawmode, why does the '(ComboBox) sender' line of code need to be there in this event handler? Isn't cboFont passed via the managed heap, not the stack, into this cboFont_DrawItem event handler? Why does it need to be cast? -hazz ,................. cboFont.Items.AddRange(FontFamily.Families); } private...
1
4861
by: Hifni Shahzard | last post by:
Hi, I got a stored procedure, where it returns a value. But if I execute it. It gives an error as "Invalid cast from System.Int32 to System.Byte.". To make clear how do I execute this, below I'm specifiying my code: The Code used in Visual Studio: Function GetRank(ByVal ID As Integer, ByVal Comp As String, ByVal Sec As String, ByVal...
8
6499
by: | last post by:
I have the following class : Public Class MyTreeNode Inherits TreeNode Dim mystring As String End Class Now, when I try to do this : ''''''''''''nodes is a TreeNodeCollection, s is string
2
11492
by: syntego | last post by:
We commonly use triggers to log changes to our main tables to historical log tables. In the trigger, we create a concatenated string of the old values by casting them as follows: CAST(O.MYDATE AS CHAR(30)) When directly updating date fields in the main table, the logged value gets saved in the format YYYY-MM-DD as expected.
11
1770
by: Dinsdale | last post by:
I am trying to determine what the current cast of an object is. Essentially, if I use GetType, it always returns the original type of the object created but I want to know what the current cast of the object is (i.e.: is it still cast as a Derived class, or is it cast as a Base class?) Here is some pseudo code to show the example. Class...
2
1667
by: D Browne | last post by:
I think this should be a very simple test but I can't figure out what the problem is: Imports ConsoleApplication1.FruitDetails Public Class FruitDetails Private m_fruitInfo As IDictionary(Of String, FruitColor) Public Property FruitInfo() Get Return m_fruitInfo
20
2877
by: raylopez99 | last post by:
Inspired by Chapter 8 of Albahari's excellent C#3.0 in a Nutshell (this book is amazing, you must get it if you have to buy but one C# book) as well as Appendix A of Jon Skeet's book, I am going through some LINQ queries. But how to cast? ( See the below, modified from somebody else's code. The problem is the query 'stops' (throws a cast...
0
7632
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...
0
7552
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...
0
7841
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. ...
0
8066
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...
1
7596
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...
0
6191
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...
0
5175
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...
0
3605
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...
1
1169
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.