|
|||||
Recent ArticlesClojure is a relatively new language to appear on the Java Virtual Machine (JVM), although it draws on very mature roots in the form of the LISP langu ... Should You Care About Requirements Engineering? Recently, I (Adil) was invited to participate in a one day seminar on the subject of Requirements Engineering. Whilst I have no direct experience of t ... Tips for Setting Up Your First Business Website To attract all potential customers to your business you need a presence on the web. The problem is that if you haven't set up a website before, you p ... LISP is a general-purpose programming language and is the second-oldest programming language still in use, but how much do you know about it? Did you ... Open Source Tools for Developers: Why They Matter From a developer's point of view use of open-source tools has advantages beyond the obvious economic ones. With the open-source database MySQL in mind ... |
What's Good About Jython?OverviewIn this article I introduce features of the Jython programming language, illustrated with a small working example. I argue the benefits of marrying Java with the Python scripting language, and then speculate why developers have been slow to adopt this innovative technology. What is Jython?Jython is an implementation of Python that is written in pure Java. This means that Jython offers all that any other implementation of Python offers (see next section), but also provides access to the whole range of Java library classes (such as Swing, JDBC, Java Cryptography, Java Speech API, and so on). It also makes it very easy to write Python code that integrates existing Java components. Conversely, it is easy to write Jython components that can later be reused and integrated into other Java-based systems. The benefit to the Java developer is rapid application development without sacrificing functionality, robustness, or the commercial respect afforded by Java. Why Python?Python is a general-purpose, object-oriented, scripting language. It is a highly regarded language that is gaining in popularity because it offers high productivity and therefore competitive advantage. It also has a simple syntax that gives rise to readable (and maintainable) programs. The language itself contains most of the constructs and features that you might expect, such as objects, functions (methods), procedural loop constructs, and exception handling. The main feature for a C or Java programmer is, arguably, the ease with which one can create and manipulate lists and sequences of values. This, coupled with idioms of functional programming such as mapping and filtering, make for a very powerful core language. A Jython ExampleAs I stated earlier, Jython is an implementation of Python that is written in pure Java. This is such a powerful idea that I'm surprised how little Jython has been recognised and adopted. Let me illustrate the marriage of the two languages with a little example. Afterwards, we can compare the equivalent source codes for Java and Jython. (If you would like to try out the example for yourself and you do not already have an installation of Jython, you can download it from the website at www.jython.org.) I will explain the example in terms of a session with the interactive shell, so that you understand not only how the source code works, but also how you might work with the Jython interpreter. So let's start up Jython's interactive shell by typing 'jython' at the command line. You should see something like the following: C:\My Jython>jython Jython 2.0 on java1.4.0 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> Now type the following at the >>> prompt: import javax.swing as swing Jython accepts the import, and simply displays the next prompt, waiting for another line of input: C:\My Jython>jython Jython 2.0 on java1.4.0 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> import javax.swing as swing >>> The import statement allows us to use the shorter package name 'swing' as the name of the javax.swing package. We can now create an instance of a JFrame, give it a title, make it visible, and assign it to a variable, f, all in one line: f=swing.JFrame(title="My Frame", visible=1) There are several features of Jython that allow this line to be so short. Firstly, we don't need to declare variables before using them. (This can be a mixed blessing, as Jython is more willing to accept typos.) Secondly, we don't use the Java keyword At this point, the JFrame is visible, so you can read its title, but it has no size. To make the window bigger, you resize it by setting the size property of the object f: f.size=(300,300) There is quite a lot going on in this short line. Firstly, the dot notation ('f.size'), combined with assignment, is a short hand for setting the
value of a JavaBean property. We could have called the Our frame still doesn't do anything, so let's first create, and then add, a button: b=swing.JButton("Push Me") f.contentPane.add(b) You'll need to redraw the frame before the button becomes visible on-screen. You can do this manually by resizing the frame with the mouse, or programmatically by calling f.repaint() Now let's make the button print a message whenever it is pressed. First, we define a function that prints a message: def printMessage(event): print 'Ouch!' Next, we associate that function with the button b. b.actionPerformed=printMessage And that's it! If you press the button, the console says 'Ouch!'. We illustrate the differences between Java and Jython code for this example by listing the source code for each. First, the Java source code: import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MyExample implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Ouch!"); } public static void main(String[] args) { JFrame frame = new JFrame("My Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button = new JButton("Push Me!"); frame.getContentPane().add(button); ActionListener listener = new MyExample(); button.addActionListener(listener); frame.setVisible(true); } } And now the Jython source code: 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 You can see how much shorter the Jython code is, even for such a simple example. Think of the implications for the cost of code development and maintenance! If you have tried out this example for yourself, or already used Jython, you will have noticed another great feature of the language - the immediate feedback you get from the interpreter. Many programmers criticize interpreted languages for executing slowly, but when it comes to speed of code development the interpreter wins hands-down over a compiler. The interactive nature of an interpreter means that you detect some errors much earlier than you would with an edit-compile-test loop. And if you can both interpret and compile code (as with Jython) then you get the best of both approaches. Jython Reuse From JavaThe example above has shown how you can access Java classes from Jython. Now I should explain how you can use Jython code from Java. The answer really is quite simple. Since Jython is an implementation of Python in Java, it needs to compile the Python functions that you write down to Java bytecode before it can run them. Normally it avoids a lengthy compilation step by doing the compilation 'on the fly', but you can also compile your Jython classes down to Java .class files or .jar archives that you can place on the classpath of your 'master' application. You perform the compilation by using the jythonc compiler provided with Jython. This compiler first generates Java source files from the Jython code, then compiles them using a standard Java compiler. If you generate .class files, then you need to remember to put the jython.jar runtime on the Java classpath when you run the master application, as the Java source files that jythonc generates have dependencies on the Jython runtime. If you generate a jar file using jythonc, however, there are options to include files from the Jython runtime within the jar. For example, if the Jython source code for the example given above is contained in the file MyExample.py, then it can be jar'ed up with the following command: jythonc -c -j myjar.jar MyExample.py This creates a jar file containing the compiled Java version of the Jython code we wrote as well as files from the Jython runtime. The jar file also contains a manifest, which makes the jar executable. You can run the jar by typing: java -jar myjar.jar Why Isn't Everybody Using Jython?This is the hard part! Jython is an incredibly powerful tool, and I think there are many developers out there who would love to use it, if only they could. It's one of those few languages that delights the developer, because the language is so powerful and you get results quickly. However, it is still very much a 'niche' language, used only by forward-thinking organisations and entrepreneurs. Here are some of the possible reasons for the low adoption rate of Jython:
ConclusionJython is a technology that marries two disparate technologies, Java and Python, seamlessly and to great effect. Unfortunately, I believe it has largely been overlooked by developers. Jython has much to offer, particularly to the Java developer community, and offers the potential to speed up conventional Java development. Related Reading:It has taken a while, but there are now a couple of good books about Jython on the market:
Simon White |