« Jesse's 得度式 (Tokudoshiki) | Main | Leaving this World »
November 5, 2007
Python: Using Lambda to Delay Argument Bindings
At the University of Minnesota the first Computer Science class is still taught in Scheme. A lot of students complain the learning an archaic functional language is a waste of time, I could not disagree more. I think it is a great introduction for many reasons but it is especially useful to programmers nowadays who are using modern procedural languages which have an increasing tendency to mix in paradigms from the functional domain.
I am working on an RPC interface for a project at the office and I found myself writing yet another function to dispatch an event callback into a sequence of calls. I wanted to have a Python library routine callback call one of my functions with the first argument statically assigned to be a value of my choosing. In other words: I needed to bind some of the argument variables immediately but allow the remainder of the arguments be left unbound. Here a bit of functional flair fit the solution: lambda function composition.
First we will create our stub dispatch function:
def dispatch(variant, *args): print "dispatch(%s, %s)" % (variant, args) # a real implementation may now act differently based on the value of variant
We want our Python library call back to call our function like so...
dispatch("type1", (0, 1, 2)) dispatch("type2", (0, 1, 2)) # etc
Using a simple lambda composition we can create a new function that has the variant argument bound while still allowing the *args array to be set at a later time. This may be done simply:
mk_cb = lambda v: lambda *a: dispatch(v, *a)
Then we can create a series of custom functions which may be registered as callbacks with whatever variant type we wish to set:
cb1 = mk_cb("type1") cb2 = mk_cb("type2")
We can call one of the callback functions just to test it:
>>> cb1((0,1,2)) dispatch(type1, ((0,1,2),))
And finally we can use it with some Python library callback registration function:
some_py_obj.register_function(cb) # cb is the dispatch() function with 'type1' as the first argument
So who says that we are, "never going to use this stuff?"
Posted by jordanh at November 5, 2007 6:14 AM |
TrackBack URL for this entry: