How do I create an array of functions?
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Mon Feb 19 17:09:26 EST 2007
On Mon, 19 Feb 2007 05:17:03 -0800, Rob Wolfe wrote:
>> > # 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?
I ran your example, word for word. Copied it and pasted it into my Python
session.
>> 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.
Actually, it wasn't easier to write at all.
Your version:
dsp = [f for fname, f in sorted(globals().items()) if callable(f)]
Sensible version:
dsp = [fun1, fun2, fun3]
Not only is your version brittle, but it is also about three times as
much typing.
--
Steven.
More information about the Python-list
mailing list