[Tutor] Using a dictionary to map functions

Peter Otten __peter__ at web.de
Tue Apr 26 08:13:56 EDT 2016


Colby Christensen wrote:

> templist = []
> pt_table = {}
> cmd_table = {5:"store_point", 19: "line_line_int"}

As Alan says, the values should be functions rather than function names.
You could use string keys to save both the re.search() check and the 
conversion to integer.

> count = 0
> 
> for line in infile:
>     #print line
>     line = line.rstrip()
>     if re.search('^[0-9]+', line):
>         a = line.split()
>         templist.append(a)
> 
> for line in templist:
>     #use dictionary to call and pass arguments to function

You could put parsing and evaluation into the same loop, and avoid the 
temporary list:

cmd_table = {"5": store_point, ...}
for line in infile:
    args = line.split()
    cmd = args.pop(0)  # remove the first item from args
    if cmd in cmd_table:
	func = cmd_table[cmd]
         func(*args)  # see below
    else:
        # optional, but may help with debugging
        print("Command {!r} not recognized. "
              "Skipping line {!r}.".format(cmd, line), file=sys.stderr)


Given a list 'args' with N items the expression

func(*args)

is equivalent to

func(args[0], args[1], ..., args[N-1])

e. g.

foo = ["one", "two"]
bar(*foo)

passes the same arguments as

bar("one", "two")




More information about the Tutor mailing list