neversaint neversaint - 26 days ago 11
Python Question

How to pass parameters in a Python Dispatch Table

I am trying to construct a dispatch the following way:

def run_nn(type=None):
print type, 'nn'
return

def run_svm(type=None):
print type, 'svm'
return


action = {'nn' : run_nn( type=None),
'svm' : run_svm(type=None),}


I want the function to be executed only when called with something like:

action.get('nn',type='foo')


With expectation it to print:

foo nn


But it breaks giving:

TypeError: get() takes no keyword arguments


What's the right way to do it?

Furthermore, two functions
run_nn()
and
run_svm()
were executed without even being called. I don't want that. How can I avoid it?

Answer

You're calling the functions while building the dictionary. You should instead put the function objects in the dict without calling them. And afterwards, get the appropriate function from the dict and call it with the keyword argument.

What you want is:

action = {'nn' : run_nn,
          'svm' : run_svm,}
...
action.get('nn')(type='foo') # get function object from dict and then call it.

I'll suggest you use action['nn'] over action.get('nn') since you're not specifying any default callable in the get method; the get method returns None when you don't specify one. A KeyError is much more intuitive than a TypeError NoneType object is not callable in this scenario.

On another note, you can drop those return statements as you aren't actually returning anything. Your function will still return without them.

BTW, I have the feeling your function(s) want to change behavior depending on type (although your type is counter-intuitive as it always a string). In any case, you may have a look at functools.singledispatch. That'll transform your function(s) into a single-dispatch generic function with the possibility to create several overloaded implementations.

Finally, although type does make for a good argument name, you may run into problems when you need to use the builtin type in your function.

Comments