[Tutor] Given a string, call a function of that name

Alan Gauld alan.gauld at yahoo.co.uk
Wed May 17 04:34:13 EDT 2017

On 17/05/17 03:49, boB Stepp wrote:

> corresponding to one of his functions or methods, if he could use that
> word to run a function of the same name.  I said I had done something
> once where I used the word as a dictionary key, which was then used to
> call the function. 

That's the usual approach.

> def check_fcn_input(function):
>     valid_fcns = ['spam', 'ham', 'eggs']
>     if function in valid_fcns:
>         return True
>     else:
>         return False

I would rewrite this to return the function or None

def get_input_function(name):
    return functions.get(name)

You can then use the result as a boolean in a
test or simply call it directly using Pythons
"ask forgiveness" approach:

name,phrase = get_input()
try: get_input_function(name)(phrase)
except TypeError: pass

> This works, but I cannot but help wondering if there is a more direct
> approach?  

Not really. Remember that Python itself uses a dictionary
to translate names to function calls. If its good enough
for the interpreter its probably good enough for you! :-)

> Hmm.  It bothers me that in check_fcn_input() I have a list valid_fcns
> and in run_fcn() I have a dictionary fcn_dict.  

A global dict wins here.
You could of course make it a class but I'm not sure that
actually makes anything clearer in this case.

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list