Turn string into function call

Grant Edwards grante at visi.com
Sat Mar 9 09:58:47 EST 2002


In article <a6crpv$f6d$1 at panix2.panix.com>, Aahz Maruch wrote:
> In article <E58i8.17062$N7.3653694 at ruti.visi.com>,
> Grant Edwards <grante at visi.com> wrote:
>>In article <1f5252d4.0203080545.3861adec at posting.google.com>, N Becker wrote:
>>>
>>> What's the best way to turn a string naming a function into a function call?
>>> 
>>> I used this:
>>> eval (funcname + '()')
>>
>>This really ought to go into the FAQ.  It's been asked (and
>>answered) at least 3 times in the past week or so.
> 
> Okay, here's a proposed FAQ entry, for section 4:
> 
> How do I convert a string to a function/method call?
> 
> There are two basic techniques:
> 
> * Use a dictionary pre-loaded with strings and functions.  The primary
> advantage of this technique is that the strings do not need to match the
> names of the functions.  This is also the primary technique used to
> emulate a case construct:
> 
>     def a():
>         pass
> 
>     def b():
>         pass
>     
>     dispatch = {'go': a, 'stop': b}  # Note lack of parens for funcs
> 
>     dispatch[get_input()]()  # Note trailing parens to call function
> 
> * Use the built-in function getattr():
> 
>     import foo
>     getattr(foo, 'bar')()
> 
> Note that getattr() works on any object, including classes, class
> instances, modules, and so on.

I think it would also be good to mention the eval() method, and
the locals() method (and the problems with both).  I started to
write up a FAQ yesterday but didn't get very far...

-- 
Grant Edwards                   grante             Yow!  I predict that by
                                  at               1993 everyone will live in
                               visi.com            and around LAS VEGAS and
                                                   wear BEATLE HAIRCUTS!



More information about the Python-list mailing list