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

boB Stepp robertvstepp at gmail.com
Wed May 17 23:03:34 EDT 2017

On Wed, May 17, 2017 at 1:42 AM, Peter Otten <__peter__ at web.de> wrote:
> boB Stepp wrote:

>> Oh, and I suppose I should ask for a critique of the code as written
>> for appropriate Python style, proper targeted function use, etc.  I am
>> always eager to learn!
>>     if function in valid_fcns:
>>         return True
>>     else:
>>         return False
> should really be spelt
> return function in valid_fcns
> and personally I wouldn't mind to type the few extra chars to make it
> return function in valid_functions


>> 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.  These contain
>> essentially the same information.  Would this be a case for a global
>> function dictionary (Which I could also use to check for valid
>> functions.) or perhaps a class which only exists to have this function
>> dictionary?
> A global is indeed better than the duplicate information in your list and
> dict. Here's another option, return the function instead of information
> about its existence:

I keep forgetting that this is doable!  I like this idea and
implemented it.  Here -- for posterity and/or further critiquing -- is
my revised code:

#!/usr/bin/env python3

def spam(phrase):
    print('spam function said: ', phrase)

def ham(phrase):
    print('ham function said: ', phrase)

def eggs(phrase):
    print('eggs function said: ', phrase)

def get_input():
    function_name = input('Which do you want:  spam, ham or eggs?\n')
    phrase = input('\nHow do you want your food to be prepared?\n')
    return function_name, phrase

def find_function(function_name):
    valid_functions = {'spam': spam, 'ham': ham, 'eggs': eggs}
    function = valid_functions.get(function_name)
    return function

def main():
    while True:
        function_name, phrase = get_input()
        function = find_function(function_name)
        if function:
        print("You made an invalid food choice!  Let's try this again!")

if __name__ == '__main__':

I cleaned up the naming a bit.  I think it reads more clearly now, and
spells out "function" fully.  Also, the overall LOC is fewer, while
retaining the same functionality.  Thanks Peter and Alan!!

BTW, my son is now merrily calling his functions using this dictionary
technique.  He seems to like it and said that he now understands both
functions, returns and dictionaries better after adapting these ideas
to his own code.  Now if I can only get him to adopt unit testing and
version control!


More information about the Tutor mailing list