How to execute the corresponding function according to the string variable?

As the title, I need to execute the corresponding function according to the different values of the string variable,

Choice_function is a function that needs to be optimized. If I have a lot of functions that need to be executed, using if else is more cumbersome. Is there any easy way to optimize the choice_function function?

My code is as follows:

def function1():
    print('function1')
    return


def function2():
    print('function2')
    return


def choice_function(name):
    if name == 'function1':
        function1()
    elif name == 'function2':
        function2()
    return


def main():
    function_name = 'function1'
    choice_function(function_name)
    function_name = 'function2'
    choice_function(function_name)
    return


if __name__ == '__main__':
    main()

Answer

  • You can use vars to do it

code:

def function1():
    print('function1')
    return


def function2():
    print('function2')
    return

vars()["function1"]()
vars()["function2"]()

result:

function1
function2
  • if you want to use it in a function like choice_function, you can use globals.
def function1():
    print('function1')
    return


def function2():
    print('function2')
    return

def choice_function(name):
    try:
        globals()[name]()
    except Exception:
        print(f"no found function: {name}")
    return

def main():
    function_name = 'function1'
    choice_function(function_name)
    function_name = 'function2'
    choice_function(function_name)
    return

if __name__ == '__main__':
    main()