Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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'))()
share|improve this question

1 Answer

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, ()))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.