Dictionary-based dispatch in Python with multiple parameters Is there a better way to express the dispatch (switch) code without using a lambda? I think I need the lambda to act as an intermediary because the functions have varying numbers of parameters.

def printf(arg):
    print arg

def printf2(arg1, arg2):
    print arg1
    print arg2

def printn(arg):
    print arg

action = 'op2'
functions = {
    'op1': lambda: printf('op1 called'),
    'op2': lambda: printf2('op2 called', 'param 2'),
    }
functions.get(action, lambda: printn('default op'))()
You could change it to just store the functions and the arguments.  Then use the argument unpacking to fill in the correct arguments to the function call.

action = 'op2'
functions = {
    'op1': (printf, ('op1 called',)),
    'op2': (printf2, ('op2 called', 'param 2')),
}

fn, args = functions.get(action, (printn, ('default op',)))
fn(*args) # call the function unpacking the provided arguments




A better solution in this particular case IMHO, rather than defining multiple functions with varying number of arguments, you could just define one function accepting variable arguments to achieve the same thing.

def printf(*args):
    if args:
        for arg in args:
            print arg
    else:
        print 'default op'


Then it's just a matter of storing only the arguments to the call rather than the functions themselves:

action = 'op2'
arguments = {
    'op1': ('op1 called',),
    'op2': ('op2 called', 'param 2'),
}

printf(*arguments.get(action, ()))