Hi.
I am trying to "convert" a string into a function pointer.
Suppose I have the following:
from a import a
from b import b
from c import c
funcString = GetFunctionAsSt ring()
and funcString is a string that contains either "a", "b" or "c".
How can I simply call the correct function?
I have tried using getattr() but I don't know what the first (object)
argument should be in this case.
Thanks,
Håkan Persson 3 5479
On Fri, 04 Feb 2005 12:01:35 +0100, Håkan Persson <ha***@zyberit. com>
wrote: Hi.
I am trying to "convert" a string into a function pointer. Suppose I have the following:
from a import a from b import b from c import c
funcString = GetFunctionAsSt ring()
and funcString is a string that contains either "a", "b" or "c". How can I simply call the correct function? I have tried using getattr() but I don't know what the first (object) argument should be in this case.
Try this: from sys import exit globals()
{'__builtins__' : <module '__builtin__' (built-in)>, '__name__':
'__main__', 'exit': <built-in function exit>, '__doc__': None} afunc = globals()["exit"]
Do you really need to use the "from X import Y" style? Consider the
following alternative:
import sys afunc = getattr(sys, "exit")
Håkan Persson wrote: Hi.
I am trying to "convert" a string into a function pointer. Suppose I have the following:
from a import a from b import b from c import c
funcString = GetFunctionAsSt ring()
and funcString is a string that contains either "a", "b" or "c". How can I simply call the correct function? I have tried using getattr() but I don't know what the first (object) argument should be in this case.
Thanks, Håkan Persson
Well, one really horrible way would be
getattr(sys.mod ules['__main__'], funcString)
and, of course, if you were going to use it a lot you could optimize
slightly with
this = sys.modules['__main__']
followed later by
this = getattr(this, funcString)
Overall, however, it might be better to set uip a mapping for the
functions you need to be accessible. This has the further merits that
a) You can heve different, and/or multiple names for a function
b) You can trap errors more easily
c) erm, I forgot the third advantage, consider this the Spanish
Inquisition in reverse :-)
So:
funcMap = {
"a": a,
"A": a,
"b": b,
"exoticName ": c }
...
funcString = GetFunctionAsSt ring()
try:
f = funcMap(funcStr ing)
except KeyError:
print "No such function"
raise SomethingElse
result = f(args)
regards
Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.pycon.org/
Steve Holden http://www.holdenweb.com/
Håkan Persson <ha***@zyberit. com> wrote: I am trying to "convert" a string into a function pointer. Suppose I have the following:
from a import a from b import b from c import c
funcString = GetFunctionAsSt ring()
and funcString is a string that contains either "a", "b" or "c". How can I simply call the correct function? I have tried using getattr() but I don't know what the first (object) argument should be in this case.
You've received a lot of hi-tech answers, but don't overlook the simple
(and possibly more secure) answer:
lookup = {
'a': a,
'b': b,
'c': c,
}
if lookup.has_key( myFunction):
return lookup[myFunction]()
else:
print "Couldn't find", myFunction
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: jagmeena |
last post by:
Hello,
I am sure this problem has been addressed before, however, I could'nt get a
suitable solution to my problem. Hence I am posting here. Thanks a lot for
all your help.
The code I have is
typedef struct Rec {
unsigned char msg;
unsigned long len;
|
by: Cyde Weys |
last post by:
I'm currently working on converting a simulator program from Visual
Basic 6.0 to Visual C++ .NET. I've figured out most of the stuff, but
there's still one thing I haven't gotten to and I've never really had
to deal with it before. I'm programming a front-end for what is a
compiled Fortran program. The VB source does the following to call
the Fortran:
'Defines the subroutine.
Declare Sub Cycle_DW Lib "cycdw.dll" Alias "CYCDW" (ByRef...
|
by: Charles L |
last post by:
I don't know if this is a stupid quesiton or not.
I would like to know how to convert an array of characters generated from a
previous operation to a string ie how do I append a null character at the
end? I haven't been able to do it so far. Is there a string function I can
use?
Can anyone help?
Charles L
|
by: songkv |
last post by:
Hi,
I am trying to reassign an array of char to a string literal by
calling a function.
In the function I use pointer-to-pointer since I want to reassign the
"string array pointer" to the string literal.
But the second printf seems to give me garbage.
Any advise on what I am doing wrong?
Thanx
|
by: Simon Schaap |
last post by:
Hello,
I have encountered a strange problem and I hope you can help me to
understand it. What I want to do is to pass an array of chars to a
function that will split it up (on every location where a * occurs in
the string). This split function should allocate a 2D array of chars
and put the split results in different rows. The listing below shows
how I started to work on this. To keep the program simple and help
focus the program the...
| |
by: diDE |
last post by:
I want to convert a managed string array
f.e. array<string^>^ Texts; // Elements 0: "ABC", 1: "HJO"
to a TCHAR** or wchar_t**
any ideas?
|
by: Terry |
last post by:
I am converting (attempting) some vb6 code that makes vast use of interfaces.
One of the major uses is to be able to split out Read-only access to an
obect. Let me give you a simple (contrived) example:
In Project RoObjDefs:
RoPerson.cls file:
Public Property Get FirstName() as String
Public Property Get LastName() as String
<end of file RoPerson.cls>
RoPersons.cls file
Public Function Count() as Integer
|
by: monomaniac21 |
last post by:
hi all
is there a function to convert all values of array $row into seperate
variables:
$row = mysql_fetch_array($result);
// i dont want to have to do this anymore :-)
$name = $row;
|
by: ling2000 |
last post by:
Hello all,
I'm trying to upgrade a VB6 project into VB.net, and the problem I had is in converting 'address of' to 'delegate'.
I had the error "Value of type 'DelegateIDccManSink_OnLogIpAddr' cannot be converted to 'integer'.",
when calling this line, ReplaceVtableEntry(.., .., callbackOnLogIpAddr).
I guess the problem is due to the VB6 expected a memory address, but the 'delegate' doesn't return an address.
Any ideas are appreciated.
|
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...
|
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...
| |
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...
|
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,...
|
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...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
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...
| |