How do I create an array of functions?

Rob Wolfe rw at smsnet.pl
Mon Feb 19 03:16:39 EST 2007


Steven W. Orr wrote:
> I have a table of integers and each time I look up a value from the table
> I want to call a function using the table entry as an index into an array
> whose values are the different functions.  I haven't seen anything on how
> to do this in python.

Do you mean something like that?

# test.py

def fun1(): return "fun1"
def fun2(): return "fun2"
def fun3(): return "fun3"

# list of functions
dsp = [f for fname, f in sorted(globals().items()) if callable(f)]
tab = range(len(dsp))
print dsp[tab[2]]()

# dictionary of functions
d = dict([(fname, f) for fname, f in globals().items() if
callable(f)])
tab = [fname for fname, f in sorted(globals().items()) if callable(f)]
print d[tab[2]]()

--
HTH,
Rob




More information about the Python-list mailing list