Converting a string to a function pointer

Steve Holden steve at holdenweb.com
Fri Feb 4 08:37:21 EST 2005


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/



More information about the Python-list mailing list