How do I create an array of functions?

John Machin sjmachin at lexicon.net
Mon Feb 19 08:55:41 EST 2007


On Feb 19, 11:47 pm, Steven D'Aprano
<s... at REMOVE.THIS.cybersource.com.au> 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.
>
> Does Python have a function that will read my mind and only return the
> objects I'm thinking of?

Yup.

Stevens_mind = r"fun[1-3]$"

After "if callable(f)", put

and re.match(Stevens_mind, fname)
and not isinstance(f, type)









More information about the Python-list mailing list