Jython, Swing & Curry
Jython is currently, by far the most useful of the the three main Python implementations, Jython, CPython and IronPython. It allows access to the Java standard library which often provides more standard, better defined, and certainly better documented alternatives to much of what is in the Python standard library. It is also more cross-platform than .NET bound IronPython and offers superior multithreading support to CPython.
Its well known within the Jython community that having first-class functions in Python makes development with Swing more productive in Jython than it is with Java, by allowing us to attach functions or methods directly to Swing callbacks such as actionPerformed, without the need for anonymous classes or excessive need for interface implementation. This example taken from What’s Good About Jython? shows this in action:
import javax.swing as swing
def printMessage(event):
print "Ouch!"
if __name__== "__main__":
frame=swing.JFrame(title="My Frame", size=(300,300))
frame.defaultCloseOperation=swing.JFrame.EXIT_ON_CLOSE;
button=swing.JButton("Push Me!", actionPerformed=printMessage)
frame.contentPane.add(button)
frame.visible=1
The most powerful result of learning different programming languages is being able to apply concepts learned in one language, in another language. This type of ‘technology transfer’ drives progress in many science and engineering fields. This cross-fertilisation has always been possible, but is becoming both more feasible and popular thanks to multiparadigm languages such as Python and Ruby, and wider use of the STL and Boost in Standard C++ which encourage and facilitate functional and higher-order programming style. There are even books on the subject of Higher Order Perl.
Although its had many notable ongoing and recent successes (e.g. Emacs, Darcs, Pugs) the functional community is unfortunately widely perceived as academic or impractical. Indeed, Guido van Rossum has recently threatened to remove some functional programming support from Python, bizarrely whilst simultaneously adding higher-order features such as decorators. This is unfortunate because functional programming style and idioms can go a long way to improving software quality in any language – functions without side-effects are far easier to test, debug and reason about.
For example, the technique of currying - fixing a function argument and returning a new function which takes the remaining parameters can be very useful for development with the Swing UI toolkit supplied with Java.
In this example extracted from one of my own projects, where the user interface features two radio buttons, we look at how some higher-order techniques can be used to aid user-interface programming with Swing. In the code below,
fixed_radio = JRadioButton(text="Regular columns of fixed width",
actionPerformed = self.handleFixedOption)
separated_radio = JRadioButton(text="Fields separated by spaces,
commas, or other characters",
actionPerformed = self.handleSeparatedOption)
two bound-methods are attached to the actionPerformed event of each button.
def handleFixedOption(self, event=None):
self.controller.setOption(self.controller.FIXED)
def handleSeparatedOption(self, event=None):
self.controller.setOption(self.controller.SEPARATED)
We don’t actually use the event parameter in this case, but it will be passed to the handler function we provide from actionPerformed, so we must accommodate it. These two methods are identical apart from the value passed to setOption internally, so we could factor out the common code and these two functions with a single function and pass the option value FIXED or SEPARATED in as an extra argument,
def handleOption(self, option, event=None):
self.controller.setOption(option)
However, we now have a difficulty in that we can no longer bind our new function directly to the actionPerformed handler of the buttons, since actionPerformed expects a function which takes single event argument. We know at coding time which option value should be attached to each button – but we don’t know until the code is run, which event will be passed from actionPerformed. We need to bind the option argument before the event argument. The solution to this is currying.
Rather than writing our own currying facility, we can use on off-the-shelf implementation provided by the Xoltar Toolkit which provides some functional programming support in Python. In particular we use the curry function to curry our handleOption function into some new functions that only take take a single event argument.
from functional import curry
fixed_radio = JRadioButton(text="Regular columns of fixed width",
actionPerformed = curry(self.handleOption,
self.controller.FIXED))
separated_radio = JRadioButton(text="Fields separated by spaces,
commas, or other characters",
actionPerformed = curry(self.handleOption,
self.controller.SEPARATED))
The curry function takes the function to be curried as its first argument. In this case we pass the bound-method self.optionHandler. The second argument to curry is the value of the first parameter to the function to be curried, which want tobe fixed to this value in the created function, for example, self.controller.FIXED. The result of the curry function is a new function which accepts one less argument than the original function – so in this case we get a new function which only accepts the remaining event parameter, and is therefore equivalent to the handleFixedOption function we started with, but which we have now avoided having to write.
The material advantage with such a simple example is minimal, but when such techniques are used throughout a project the savings in space and complexity can be substantial. The combination of functional concepts from borrowed from languages such a Haskell, facilitated by tools provided by the Xoltar Tookit, developed in dynamically-typed Jython and exploiting one of the better designed user interface APIs in the form of Swing can be concise and powerful.

This article in the ASPN Python Cookbook also discusses currying with respect to user-interface callbacks:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
interesting to see some discussion on Jython and Swing…since I am new to the Jython arena (coming from Java/Swing and Python).
gonna add this site to my rss reader…hope to hear more!
Robert,
A nicely-balanced posting; I think it’s because you’re a C++ programmer “by trade” and a software engineer (we need a better term for this) “by preference”.
I like C++. In fact, I love C++. I got to this post via googling for lambda and currying functions in C++ (naturally, you can find the former in Boost, but the latter are lagging behind) largely because I’m getting sick of the boilerplate code for functors, not to mention the occasional need for what limited set of bindings exist in the STL…
… which is really the problem I think you’re addressing. I might be an old C++ fart, but I do try to think of other paradigms where they exist. (Or, indeed, don’t.) Most “C++” programmers aren’t C++ programmers at all. Generally, they’re not even very good C programmers. In fact, I wouldn’t necessarily rely on them as programmers — they tend to come from a maths, physics or engineering background, which starts them off with a set of unnecessary preconceptions such as “unroll that loop,” “in-line that function,” “tote that barge…” etc. Given the technical ability and general timidity of management, as you say, this quickly sets into a concrete mind-set that doesn’t adapt particularly well to new application domains.
I mean, who on earth would hand-craft an XML parser in C++?
Mind you, the concept of people being taught in Java at college and then being told to use C++ at work is equally bizarre to me. I really don’t think Java is a good teaching language. (Strangely, I think C++ is — precisely because its syntax, etc, is so difficult.)
Anyway, as a recent emigre from the C++/perl world to the C++/python world, I’m hoping to investigate jython more. It has blindingly obvious benefits (not least, as you say, its cross-platform capabilities, although rival JVM producers seem hell-bent on reducing these).
My fondest job memory was of a 4000 transactions/second system written in C++ (and reasonably free of bugs, apart from a couple of very nasty ones that someone else fixed). I don’t get to do this sort of thing any more. Instead, I get to design and code dynamic Web systems. I don’t think that C++ is particularly well-adapted to the issues involved here. I definitely need to branch out into the areas you’re discussing.
Thanks! Keep writing…
“Jython is currently, by far the most useful of the the three main Python implementations”
If you’re mostly doing Java, I suppose. But there’s so much useful stuff written in CPython that Jython feels like a second stringer.
I do both, and Jython is great, but CPython is more useful for general work. Jython is only really useful for Java scripting. I would never write an entire application in Jython, I would wind up implementing most of the core in Java for speed and reuse.