Home > database >  Python dynamic function design based on input
Python dynamic function design based on input

Time:10-08

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.

CodePudding user response:

Python also has a switch-case like structure now called match. Which is not an entirely new design or structure, it just feels a little cleaner imo.

def main(input):
    result = 0
    match input:
        case 'a':
            result = function_a()
        case 'b':
            result = function_b()

CodePudding user response:

Even considering the introduction of match statements in Python 3.10, I find the dictionary approach to be effective for simple scenarios.

Adding new "match/case" blocks is as easy as adding another key-value pair. And you can even use a try/except block to catch the KeyError and handle invalid input.

Example:

def main(input_string):
    try:
        result = {
            'a': function_a, 
            'b': function_b,
            # add other cases here
            'z': function_z,
        }[input_string]()
    except KeyError:
        print(f'Got an invalid input: {input_string}')
    # ... etc

CodePudding user response:

You can use "getattr", add all functions in one class and pass this class to getattr and also the letter:

class Definations:
    def function_a():
        return 'output: a'

    def function_b():
        return 'output: b'
  
    
def main(input):
  obj = getattr(Definations, f'function_{input}')
  return obj()
    
print(main('a'))
  • Related