Overview
In 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 Example
As 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 new
for
creating an instance of a class. Thirdly, properties can be set on a
JavaBean at the time of its creation by passing them as keyword
arguments. Here, we are setting two properties: the name of the JFrame,
and its visibility. Note that Python does not have a Boolean type, as
in Java, so we must supply the visibility value as 0 (false) or 1
(true).
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 setSize()
method directly on f (as in f.setSize(300,300)
), but using the dot notation for setting property values can lead to more concise code.
Note that we did not explicitly create an instance of the java.awt.Dimension
class
before assigning it to the size property. Jython knows to expect a java.awt.Dimension
object, and
therefore passes the tuple (300, 300) as an argument to the constructor of the Dimension class to
create a new Dimension object. The newly created Dimension object is then set as the value of the
size property.
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 Java
The 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:
- Two Technologies, One Developer
- It won't have escaped your notice that to understand a Jython program
(or to be more precise a Jython program that uses Java classes)
you need a solid understanding of both Java and Python. This places
demands on the skills of the developer at a time when most managers
prefer to simplify code development by choosing the technology that
is the common denominator across their applications. - Learning Curve and Project Pressures
- Most developers come to Jython from Java, so have to learn about Python.
They probably have to learn Python before being able to convince colleagues
and managers that Jython will save time in the long run. And the time to
learn a new language in the midst of project pressures and approaching
deadlines is simply not available. It?s a vicious circle that needs to be
broken, and I'm confident that for many, an investment in Jython will pay off. - Old Habits Die Hard
If you're a Java developer, you are probably quite satisfied developing Java.
It's a good, well established, programming language and you?re familiar with
the idioms, patterns and style of the language that make it elegant.
Why should you change? Well, I think you should at least consider using Jython,
because firstly, Python, too, is a good programming language with a strong
following. Secondly, a good developer should always be on the look-out for
ways of becoming more productive, and I believe Jython is a good candidate.
Lastly, technologies in the IT sector are always changing, so you should
constantly re-evaluate your technology choices to be sure that you use
your chosen technologies for the right reason, instead of 'choosing' them
by default because "that's what you do".- Perception of an "Experimental Technology"
- Jython is not an "Experimental Technology" -
It is industrial-strength and stable. If you're not confident enough to
use it for your main application straight away, then use it for writing
test scripts and developing prototypes. Often, developers will begin with
the intention of writing a prototype in Jython and later migrating to Java,
only to find later that the migration is not necessary. - Jython is Slow
- To say that Jython is unsuitable for your application because it is
an interpreted language and therefore too slow is almost certainly false.
There are very few applications these days for which execution speed is
such a major concern. And if you do find a bottleneck in your code you
can always migrate that section of code to Java as necessary. As a
developer, you should be more concerned about the speed of development
than the speed of execution, and in this respect, Jython is fast!
Conclusion
Jython 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:
Jython Essentials by Samuele Pedroni & Noel Rappin. Published by O'Reilly, 2002. See listing at Amazon.com or Amazon.co.uk | |
Jython for Java Programmers by Robert Bill. Published by New Riders, 2002. See listing at Amazon.com or Amazon.co.uk |
Powered by ScribeFire.
No comments:
Post a Comment