[Tutor] apply() vs. the extended call syntax
Tim Johnson
tim at akwebsoft.com
Sat Aug 3 01:34:45 CEST 2013
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 ....
thanks
--
Tim
tim at tee jay forty nine dot com or akwebsoft dot com
http://www.akwebsoft.com
More information about the Tutor
mailing list