Sep 23 2005

Python Dispatch Tables

Published by Chris McAvoy at 3:42 pm under Python

Hot on the heels of yesterday’s HOP reading, I was thinking about how to implement a dispatch table in Python. For a little while I thought it would be awkward at best, without all the fancy references that Perl relies on. As an experiment, I opened up an interpreter and ran:


In [1]: def sum(num1, num2):
...: return num1 + num2
...:

In [2]: sum(1,1)
Out[2]: 2

In [3]: i = [sum,]

In [4]: i
Out[4]: [<function sum at 0xb7b7bf7c>]

In [5]: i[0](1,1)
Out[5]: 2
</function>

Yikes. That was easy. I’ve done a sort of dispatch table with compiled regex’s in Python, but I’ve never tried putting a function in there. I’m not sure why I doubted it would work.

I wrote a little email parser for my improv team yesterday. It updates our rehearsal schedule based on the email subject line. So something like, “chris 9/27 out” removes me from the list of people attending that rehearsal. “chris 9/27 in” puts me back in. It’s a goof robot that I’m hoping fixes a scheduling problem we’ve had for a while now. The line is parsed, broken up, and then sent through a gauntlet of if – thens until it finally arrives at the command that needs to be run.

At the time, I knew I was probably doing this in a not robust way, but I forged ahead, wanting to just get it done. The dispatch table concept is going to make it a lot easier to add commands to the robot without much fuss. Neat.


Share and Enjoy:
These icons link to social bookmarking sites where readers can share and discover new web pages.

  • del.icio.us
  • digg
  • Reddit
  • StumbleUpon

Trackback URI | Comments RSS

Leave a Reply