dispatch tables in Python 2.4

Michele Simionato michele.simionato at gmail.com
Sat Aug 7 16:25:30 CEST 2004


<Still experimenting with the new features of Python 2.4 ...>

A thing I always had in my wishlist was the ability to define dispatch
tables in an elegant way. Currently, Python is butt ugly:

def function_with_a_long_name_1():
    "do this"
    
def function_with_a_long_name_2():
    "do that"
 
dispatch_table = dict(
 function_with_a_long_name_1 = function_with_a_long_name_1,
 function_with_a_long_name_2 = function_with_a_long_name_2,
)

Really horrible and error prone (especially for a poor typist like
myself). With decorators I can do

def add_to(lst):
    def closure(func):
       lst.append(func)
       return func
    return closure

lst = []

@add_to(lst)
def function_with_a_long_name_1():
    "do this"

@add_to(lst)
def function_with_a_long_name_2():
    "do that"

dispatch_table = dict((f.func_name,f) for f in lst)
#!generator-comprehension!

With the advent of decorators I see myself using more and more
closures.

BTW, what's the status of the so called "functional" module? I think
there
was a rumor of such a module scheduled for Python 2.4 or 2.5. To play
with
decorators we really need some standard way to compose functions and
to do
partial application of arguments.

Just my 2c,


          Michele Simionato

P.S. decorators make also easy to abuse classes for making dispatch
tables:

class DispatchTable(object):

   @staticmethod
   def function_with_a_long_name_1():
      "do this"

   @staticmethod
   def function_with_a_long_name_2():
      "do that"


But I somewhat prefer dispatch_table[function_name] over
getattr(DispatchTable, function_name).



More information about the Python-list mailing list