Converting a string to a function pointer
John Machin
sjmachin at lexicon.net
Fri Feb 4 06:52:58 EST 2005
On Fri, 04 Feb 2005 12:01:35 +0100, Håkan Persson <hakan at 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")
More information about the Python-list
mailing list