vendredi 7 octobre 2022

Python dynamic function design based on input

Suppose I have 26 functions and one of them calculate some formulas. Let's call them function_a, function_b, ..., function_z.

In my main function, I need to choose which function_{a...z} to use based on the given input.

I wrote the following function.

def main(input):
    result = 0
    if input == 'a':
        result = function_a()
    elif input == 'b':
        result = function_b()
    ...

    elif input == 'z':
        result = function_z()

Or I have a long dictionary like below, and choose the function to use based on the input.

{'a': function_a, 'b': function_b, ... , 'z': function_z}

However, are there any better designs / structures?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire