0

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()

1
  • 3
    Consider using a dictionary where the keys are function_name and corresponding values refer to the appropriate function. Call your dictionary D then D['functions1']() Of course this will fail miserably if the key doesn't exist. You should account for that Commented Aug 26, 2021 at 7:21

1 Answer 1

1
  • 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()
Sign up to request clarification or add additional context in comments.

1 Comment

Sole vars() merely produces globals() and should be replaced with such.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.