[Tutor] easy way to populate a dict with functions
bob gailer
bgailer at gmail.com
Thu Aug 6 22:20:26 CEST 2009
Albert-Jan Roskam wrote:
> Hi Bob,
>
> Very neat solution, thanks a lot! I didn't know the inspect module, but it's just what's needed here. Cool!
Great.
Regarding the ordering of functions in the list - variable names in
namespaces (such as modules) are stored in dictionaries. Any ordering is
lost in this process. Why is order important to you here?
There are other things that could be said about your program and my
revision.
1 - it is better to have functions return values and have the main
program decide whether to print them or take some other action. (Also
note you were not consistent - foo returns the others print!)
2 - since the list contains the function names as well as references to
the functions you could present the names to the user. You could even
ask the user to enter the first letter(s) of the names instead of a number.
3 - with a slight enhancement to things you can preserve the order:
# -------- commands.py ---------------
cmds = []
def collect(func):
'a "decorator" that adds each function to the cmds list'
cmds.append((func.__name__, func))
@collect
def foo (a):
return "foo" * a
@collect
def bletch (q):
for i in range(20):
return i * q
@collect
def stilton (n):
return "yes sir, " * n
@collect
def romans (z):
return "what have the romans really done for us?\n" * z
# -------- end code ---------------
# -------- main.py ---------------
import commands
cmds = commands.cmds
# etc.
--
Bob Gailer
Chapel Hill NC
919-636-4239
More information about the Tutor
mailing list