function jumptable idiom

Fredrik Lundh effbot at
Thu Mar 9 18:27:42 CET 2000

Brian E Gallew wrote:

Content-Type: multipart/signed; protocol="application/pgp-signature";
 boundary="pgp-sign-Multipart_Thu_Mar__9_11:27:24_2000-1"; micalg=pgp-md5

(now that's a great way to make sure your messages
don't show up in some agents.  maybe you didn't want
the bots to see your post? ;-)

> I'm building a program with an interactive loop in it, along with a
> trivial parser.  What I'm doing is this:

>     cmd = command_list[words[0]]
>     cmd(words[1:])

> However, that means that all of the functions in the jumptable have to
> assume that they will always get one argument (a list).  Is there a
> more natural way to express this?

maybe you could use apply?

    cmd = command_list[words[0]]
    apply(cmd, tuple(words[1:]))

(don't forget to add try-except to make sure your
program doesn't stop if user forgets an argument
or two...)

alternatively, you can use the cmd module:

here's an example (from the eff-bot guide; see below for
more info):


import cmd
import string, sys

class CLI(cmd.Cmd):

    def __init__(self):
        self.prompt = '> '

    def do_hello(self, arg):
        print "hello again", arg, "!"

    def help_hello(self):
        print "syntax: hello [message]",
        print "-- prints a hello message"

    def do_quit(self, arg):

    def help_quit(self):
        print "syntax: quit",
        print "-- terminates the application"

    # shortcuts
    do_q = do_quit

# try it out

cli = CLI()

# end

and here's some output:

> help
Documented commands (type help <topic>):
hello           quit

Undocumented commands:
help            q

> hello world
hello again world !
> q

hope this helps!


<!-- (the eff-bot guide to) the standard python library:

More information about the Python-list mailing list