[Tutor] Iterating through a function list
Dave Kuhlman
dkuhlman at rexx.com
Wed May 20 23:39:40 CEST 2009
On Wed, May 20, 2009 at 10:02:22AM -0400, Robert Berman wrote:
>
> Hi,
> Given a list of options: option_1.......option_n. For each option I
> have a corresponding function: func_1..... func_n. I have all function
> names defined in a list similar to flist = [func_1,
> func_2,.......func_n] which I know is a legitimate construct having
> found a similar construct discussed by Kent Johnson in 2005.
> What I do not know how to do is to call the selected function. If the
> index of options is 1, then I want to call func_2; do I code
> flist[index]?
Yes.
Then to call that function, do:
flist[index](arg1, ...)
or do:
func = flist[index]
func(arg1, ...)
Similarly, if you need to look up a function by name or some other
key then use a dictionary. For example:
funcs = {'func_name_one': func1, ...}
if name in funcs:
funcs[name](arg, ...)
Python is making this too easy for you, making it hard to spot the
solution.
Think of parentheses as a "function call operator", which you can
apply to any callable value.
- Dave
--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
More information about the Tutor
mailing list