How do I create an array of functions?

Rob Wolfe rw at smsnet.pl
Mon Feb 19 08:17:03 EST 2007


Steven D'Aprano wrote:
> On Mon, 19 Feb 2007 00:16:39 -0800, Rob Wolfe wrote:
>
> >
> > 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)]
>
> Hmmm... when I try that, I get dozens of other functions, not just fun1,
> fun2 and fun3. And not just functions either; I also get classes.

Oh, really? Where are these _other_ functions and classes
in *MY* example?

> Does Python have a function that will read my mind and only return the
> objects I'm thinking of?

Your sarcasm is unnecessary.
Using of `globals` function was easier to write this example.
That's all.

--
Rob




More information about the Python-list mailing list