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?
You're calling the functions while building the dictionary. You should instead put the function objects in the dict without calling them. And afterwards,
getthe appropriate function from the dict and call it with the keyword argument.What you want is:
I'll suggest you use
action['nn']overaction.get('nn')since you're not specifying any default callable in thegetmethod; thegetmethod returnsNonewhen you don't specify one. AKeyErroris much more intuitive than aTypeErrorNoneType object is not callable in this scenario.On another note, you can drop those
returnstatements 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 yourtypeis counter-intuitive as it is always a string). In any case, you may have a look atfunctools.singledispatch. That'll transform your function(s) into a single-dispatch generic function with the possibility to create several overloaded implementations.Finally, although
typedoes make for a good argument name, you will run into problems when you need to use the builtintypein your function.