[Tutor] How to pass varying number of arguments to functions called by a dictionary?

Dave Angel davea at davea.name
Wed Feb 11 15:45:53 CET 2015


On 02/11/2015 08:27 AM, boB Stepp wrote:
> Python 2.4.4, Solaris 10
>
> I have a file of functions. Based on what is read in a data file,
> different functions in the file of functions will need to be called. I
> have been trying to make the following approach work, so far
> unsuccessfully as, in general, each function may have a different
> number of arguments that might have to be passed to it.
>
> def func1(x1, x2, x3):
>      pass
>
> def func2(y1, y2):
>      pass
>
> def func3(z):
>      pass
>
> call_fcn = {'a': func1, 'b': func2, 'c': func3}
>
> call_fcn[key_letter](???)
>
> How can I successfully pass the needed arguments needed for each
> possible function with this approach? I naively tried to do something
> like:
>
> pass_args = {'a': (x1, x2, x3), 'b': (y1, y2), 'c': (z)}
> call_fcn[key_letter](key_letter)
>
> But ran into the syntax error that I was giving one argument when
> (possibly) multiple arguments are expected.
>
> Is what I am trying to do a viable approach that can be made to work?
> Otherwise, I will brute-force my way through with if-elif-else
> statements.
>
> Thanks!
>

Sure, it's viable, but the best approach depends on your goal (use 
case), and your restrictions.  Are these functions really totally 
unrelated to each other?  You not only don't have the same number of 
arguments, but the values don't even have anything in common?

There's an implied constraint that you're not permitted to change the 
functions.  Are you really constrained to only change the caller?

Assuming that you seriously want to be able to do this, the only use 
case I can imagine are:
    1) you're writing an interpreter
    2) you're interfacing some network channel, where something at the 
opposite end is sending you messages that you have to turn into local 
function calls, and return results.  A kind of RPC.

In each case, there are probably better ways.  But you want this way, so 
here goes:  (code is untested)

pass_arg_dictionary = {'a': (x1, x2, x3), 'b': (y1, y2), 'c': (z)}
pass_args = pass_arg_dictionary[key_letter]  #a list
call_fcn[key_letter]( *pass_args )


-- 
DaveA


More information about the Tutor mailing list