473,503 Members | 2,174 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting a string to a function pointer

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 = GetFunctionAsString()

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
Jul 18 '05 #1
3 5467
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 = GetFunctionAsString()

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")


Jul 18 '05 #2
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 = GetFunctionAsString()

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.modules['__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 = GetFunctionAsString()
try:
f = funcMap(funcString)
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/
Jul 18 '05 #3
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 = GetFunctionAsString()

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.
Jul 18 '05 #4

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

Similar topics

4
5404
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 ...
4
3296
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...
14
12898
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...
4
5371
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...
4
8775
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...
4
2800
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?
9
2538
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)...
11
6659
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;
0
1367
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'...
0
7205
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
7093
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...
0
7349
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
7008
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...
1
5022
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
3177
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...
0
1521
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 ...
1
746
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
399
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...

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.