[Tutor] apply() vs. the extended call syntax

Peter Otten __peter__ at web.de
Sat Aug 3 08:32:46 CEST 2013


Tim Johnson wrote:

> Frequently I use a function dispatch approach like this:
> funcs = {"key1":func1,"key2":func2}
> 
> ## and call one of those functions with a key value
> ## as follows
> funcs[key](some,fixed,number,of,arguments)
> 
> Less frequently, I might want to dispatch functions with variable
> numbers of arguments.
> 
> Follows is an illustrative (hopefully) REPL session
> ## define a couple of simple function
> def test_apply(one,two): print(str(one) + " " + str(two))
> def func_two(): print("I don't have an argument!")
> 
> ## define references to one or more functions and argument lists
> ## of variable lengths
> 
> func_D = {"key1":(test_apply,("one","two")), "key2":(func_two,())}
> 
> ## give a key some value
> k = "key1"
> 
> ## Use the deprecated apply() function first
> apply(*func_D[k])
> one two  ## yup, that's what I was looking for!
> 
> ## Now use the extended call syntax
> func_D[k][0](*func_D[k][1])
> one two
> ## also what I was looking for, but yuck!
> 
> Is there a cleaner way to do this? using apply()
> looks so much simpler, but I understand it is not even available in
> py 3 ....

I'd say

func, args = func_D[k]
func(*args)

looks pretty clean. Alternatively, if the arguments are fixed anyway, change 
the dict to store only no-arg functions. You can make them on the fly with 
lambda expressions or functools.partial():

from functools import partial

func_dict = {
   "key1": partial(test_apply, "one", "two"),
   "key2": func_two,
   "key3": lambda: foo + bar/baz,
}
...
func_dict[k]()




More information about the Tutor mailing list