Converting a string to a function pointer

Tim Roberts timr at probo.com
Sun Feb 6 23:43:04 EST 2005


Håkan Persson <hakan at 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, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list