0

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.

3 Answers 3

1

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

Comments

1

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

Comments

0

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

Comments

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.