mercredi 24 mars 2021

Is there an elegant way to manage multiple related functions through one big function? [duplicate]

I have n different functions that are all highly related but take slightly different arguments.
As a metaphor, consider that they represent n different sorting algorithms. Now, I want one big parameterized function sort which is called from the outside and then internally calls the correct sorting algorithm / the correct function.
As an additional requirement, it must be possible to give all these subfunctions different input information (different number of arguments).

I came up with a solution but I feel like this is bad style.. can anyone with more experience give his/her thoughts to this solution?

def function_one(*args):
    arg1, arg2 = args[0:2]
    # do something here
    
def function_two(*args):
    arg3, arg4 = args[2:4]
    # do something here

# imagine that here are more functions

def function_n(*args):
    arg1, arg3, arg5 = args[0], args[2], args[4]
    # do something here

switcher = {
    'one': function_one,
    'two': function_two,
    # ... imagine that here are more mappings
    'n': function_n
}

def some_super_function(arg0, arg1=None, arg2=None, arg3=None, arg4=None, arg5=None, ..., argN=None):
    return switcher.get(arg0)(arg1, arg2, arg3, arg4, arg5, ..., argN)

Aucun commentaire:

Enregistrer un commentaire