Converting a string to a function pointer

Robert Brewer fumanchu at amor.org
Fri Feb 4 11:35:54 EST 2005


Håkan Persson 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.

If you want to avoid typing all of the "import" statements, use something like my public-domain xray module (http://www.aminus.org/rbre/python/xray.py) and then write:


import xray
funcString = GetFunctionAsString()
func = xray.functions(funcString)
func()

Dotted-package names work with that module, by the way.

The benefit is that you can then import any function in any module.
The curse is that you can then import any function in any module. ;)


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list