Jython makes Drools declarations more palatable

Sunday 13 March 2005 at 12:08

I've been trying to play around with drools in fits and starts for over a year now or maybe longer. My first exposure to a rule engine was at PlanetCAD. We were going to integrate Envoy with some code which I mostly didn't like but had the redeeming quality that they used Jess for declaring pricing rules.

I wanted to play with Drools, but I just can't stand the XML syntax for declaring rules. It mixes angle-brackets with code blocks. You can choose a few different languages for use in the code blocks, but it still looks too much like JSP without JSTL. (Bob, aren't you the one who said "I hate programming in angle brackets"?) More importantly, I'm just tinkering with this stuff to get my head thinking in rules and Java doesn't feel like the right language for tinkering.

To that end I have written some code in jython to enable me to play with Drools with a pleasant python syntax. It's been kinda fun working on it in small doses after Elliott goes to bed.

Jython and Drools

I'm pretty amazed at how little code I needed to write. That could be a good sign. For your comparing pleasure, I wrote up a couple of the drools examples using my python syntax:

State Example: drools jython

Fibonacci Example: drools jython

The problem of translating this work to Groovy is left as an exercise for James Strachan. ;-) A project for the lazy web is to do something similar with Jess.

Update: Oh, the horror. Jython 2.1 doesn't do closures! The following code works okay in CPython 2.3, but throws an error in Jython:

import unittest

def fn_factory(x):
    def fn(y): return x + y
    return fn

class TestClosure(unittest.TestCase):
    def test_fn(self):
        fn = fn_factory(5)
        for i in range(3,10):
            self.assertEquals(fn(i), i + 5, 'i=%s fn(i)=%s'%(i, i+5))

if __name__ == '__main__':

There are ways to work around this, but they're all ugly and the whole point was to get away from ugly. I was so disappointed as I was debugging this and searching the web for more details. Sigh. It's pretty hard to do without closures once you get used to thinking that way. The alternatives seem so messy. A rev of Jython can't come too soon as far as I'm concerned.