dispatch tables in Python 2.4

  • Thread starter Michele Simionato
  • Start date
M

Michele Simionato

<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).
 
P

Paul Moore

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.

PEP 309 is marked as "Accepted", and an implementation patch exists.
The PEP needs updating, and there are possibly a few more procedural
things to do before the code is checked in. I emailed the author of
the PEP on Friday, asking about this. I think it's mainly lack of
tuits.

The PEP only covers partial application, BTW.

Paul.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top