473,737 Members | 9,590 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 1445
"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
5950
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
1449
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 directly. However I don't know what is the type for Request and Payload (These will be versioned...
17
2674
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 void cboFont_DrawItem(object sender,
1
4905
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 iDate As Date) As String 'Dim Ret As Integer
8
6509
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
11514
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
1785
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 Base .... End Class
2
1675
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
2907
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 exception) at "3", and never gets to "violet".
0
8968
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
8786
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
9470
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
9334
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
9258
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
9207
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
8207
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
4823
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2744
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.