[Tutor] easy way to populate a dict with functions

bob gailer bgailer at gmail.com
Thu Aug 6 19:28:19 CEST 2009


Please start a new email when starting a new topic. Otherwise it gets 
linked to the previous one in email clients that follow threads!

To avoid that here I am responding in a new email. Also fixed spelling 
in subject.

Albert-Jan Roskam wrote:
> Hi,
>
> I was playing with the code below, and I was wondering if there was a way to populate the dictionary called 'commands' (in the function 'check_command()').
>
> Suppose I would add another function, which I would also like to store as a value in 'commands', could it simply be programmed, or would every update/addition require the definition of the dictionary to be extended?
> It would be most desirable if one could simply add another function without there being the need to touch any of the other code. 
>
>
>   
Here's how I'd do it. Others may have other solutions.

Put the command functions in a separate module, e.g., commands.py:
# -------- code ---------------
def foo (a):
  return "foo" * a

def bletch (q):
  for i in range(20):
    print i * q

def stilton (n):
  print "yes sir, " * n

def romans (z):
  print "what have the romans really done for us?\n" * z
# -------- end code ---------------

Put the "main" program (in another module) e.g., main.py:

# -------- code ---------------
import commands
import inspect
cmds = inspect.getmembers(commands, inspect.isfunction)
num_cmds = len(cmds)
option_list = "|".join(str(c) for c in range(1, num_cmds+1))
prompt = "choose an option [%s]: " % option_list

def check_command():
  while True:
    select = raw_input(prompt)
    try:
      command = cmds[int(select)][1]
    except ValueError:
      print "non-numeric option     (%s)" % select
    except IndexError:
      print "option out of range (%s)" % select
    else:
      check_parameter(command)
      break

def check_parameter(command):
  while True:
    parameter = raw_input("choose a parameter [integer]: ")
    if parameter.isdigit():
      command(int(parameter))
      break
    else:
      print "illegal parameter (%s)" % parameter

check_command()
# -------- end code ---------------

cmds is a list similar to:
  [('bletch', <function bletch at 0x011BA2B0>),
  ('foo', <function foo at 0x011AF9B0>),
  ('romans', <function romans at 0x011BA330>),
  ('stilton', <function stilton at 0x011BA2F0>)]

-- 
Bob Gailer
Chapel Hill NC
919-636-4239



More information about the Tutor mailing list