Turn string into function call

Aahz Maruch aahz at panix.com
Sat Mar 9 06:31:11 EST 2002


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.
-- 
                      --- Aahz  <*>  (Copyright 2002 by aahz at pobox.com)

Hugs and backrubs -- I break Rule 6                 http://www.rahul.net/aahz/
Androgynous poly kinky vanilla queer het Pythonista

"Argue for your limitations, and sure enough they're yours."  --Richard Bach



More information about the Python-list mailing list