March 4, 2021
Hot Topics:

Introduction to Jython

  • By Developer.com Staff
  • Send Email »
  • More Articles »

What's Jython Good For?

Having seen the interactive example, hopefully you are interested in learning more about Jython. But you may be wondering exactly what you might use it for. It can help to think of the JVM as a platform in its own right. Java has been the overwhelming choice of programming language for the JVM platform--a number of different languages other than Jython run under a JVM in one way or another, but for most people, so far, the JVM and Java programming have been effectively synonymous. Uses of Jython can be split into two areas: things you might want to do within a JVM for which Java is not a great choice, and things you might want to do where Java does seem like a strong choice.

In the first category are the kinds of programs at which scripting languages have traditionally excelled. Programs that are small utility tools, or one-time-only scripts, or rapid development prototypes, have all been in the purview of scripting languages such as Python. The Java language, for all its usability benefits over, say, C++, was not designed for that kind of rapid development or scripting work. Jython makes that kind of programming easier on a JVM, giving you scripting language flexibility where it did not exist previously. This also suggests a place for Jython as an adjunct to existing Java programs--performing cleanup and maintenance functions, for example.

Web programming is another area in the first category. Java has made tremendous strides as a server-side web application tool over the last few years, primarily because of the creation of really good industrial-strength server environments. Writing the actual web application in Java, however, is still a chore, especially when maximum response to changed requirements is needed. Outside the Java world, many (if not most) web applications are still written in dynamic scripting-style languages such as ColdFusion, Perl, or Python. It's no accident that template languages or other scripting languages written specifically for Java web applications have proliferated. Jython as a web language gives you a scripting language that is more powerful and established than other Java web tools such as WebMacro or Tea, yet still gives you full access to the Java servlet libraries.

Another area that Java doesn't really cover is the use of a scripting language by your Java program. The Jython interpreter can be embedded inside any Java program, allowing you full access to Jython for scripting inside the program. One use of this feature common in Python is to have your preference or properties file be a "live" Jython script, saving you the trouble of having to convert a properties or XML file to actual functionality.

We do not, however, want to give you the impression that Jython is good only for tasks that Java is weak at. In fact, we also think that you will find Jython useful even for the kinds of applet or GUI applications traditionally thought of as Java's strengths. We believe that if you decide to prototype your program in Jython, there is a very good chance that you will find that development of the Jython version is so smooth, you will keep the prototype rather than port it to Java.

The Benefits of Jython

We think that Jython is likely to improve your productivity for a great number of project types that are currently performed in Java. In this section, we'll start to explore the reasons why we believe this to be true. We'll also suggest some reasons why Jython might be a good addition to your toolkit even if you are already a CPython programmer.

For Java Programmers

If you are already programming in Java, you are probably wondering why you need another language to run under the JVM. Doesn't Java work just fine? Sure, Java is great. But, by using Jython instead of Java, you'll probably find that the number of lines of code in your program has dropped by as much as 50%. Many empirical studies of programming suggest that shorter programs have fewer bugs. In addition, programmer productivity tends to be about the same for any number of lines of code even if, as in Jython, each line of code tends to do more than it might in another language. In other words, an expert Jython programmer will likely produce programs faster, and with fewer bugs, than an expert Java programmer.

We don't mean to attack Java as a programming language. Java, like every programming language, is a tool, and it has its uses. However, it's hard to use Java for any length of time and not realize that it is an exceptionally verbose and often inflexible language. After you've written lines of code such as the following, which includes a typecast that is there only to keep the compiler happy:

MyClass instance = (MyClass)list.get(2);

it becomes easier to see the benefits of just writing:

instance = list[2]

The difference between the Java and Python code emphasizes one of the main sources of the productivity advantage of Jython--dynamic typing. In Python, you do not need to declare variables for use, nor do you need to tell the interpreter what the expected data type of a variable is. It is important to note that despite being dynamically typed, Python also has strong typing. This means that a line of code such as "1" + 1 is an error in Python (unlike many other scripting languages, which would quietly allow this).

If you have never programmed in a dynamic language, the idea of not declaring variables or types may make you a little nervous. After all, isn't the point of static typing to allow the compiler to catch errors before the program runs? It's certainly true that static typing can do that. Most programmers who switch to a dynamic language are surprised by how rarely those errors actually occur in practice, and how quickly they are usually found and fixed when they do occur.

In Python most type errors are caught immediately the first time you run the program--long before any users see it. Often type mistakes will result in errors the first time a module is loaded or the first time a function is called. Some basic unit testing makes it nearly impossible for a type check error to get by. When compared with the amount of effort spent in Java convincing the compiler that your program is legal, it seems that static typing may not be worth the effort. It's worth your time to try it and see if your experience is similar to ours.

In addition to dynamic typing, the Python scripting language used in Jython offers several other features that will improve your programming productivity:

Clean, easy-to-read syntax
Python was designed from the ground up to be as readable as possible--it's been described as "executable pseudocode." Python's use of indentation to denote block boundaries makes for consistent and clear code. Unlike some other scripting languages, Python syntax tends to be in words rather than typographical syntax--it's very unlikely you'll be writing lines of code that look like comic book curse words. As a result, when you have to come back to your code six months later, odds are you will still be able to understand it.

Interactive interpreter
Jython has a command-line interpreter where you can enter any Jython expression (including function definitions, class definitions, and module imports) and evaluate it interactively. The interactive session makes it easy to test and debug Jython code and also to explore existing Java libraries by trial and error.

Module-based organization
Unlike Java, where every line of code has to be inside a class definition, Jython separates the package organization from the class system. A Jython module can contain any valid statement, including class and function definitions as well as normal program code. The lack of insistence on structure is particularly nice in short scripts, but also helpful for distributing a number of related classes together.

High-level, built-in types
Jython's list of basic types includes a few that go beyond Java's basic data types. These include sequence types similar to Java collection classes and dictionaries similar to Java's map classes. Having these types built into the language makes them easier to work with--you can enter an entire dictionary as a literal expression, for example. Jython also includes a built-in file type which is far easier to use than Java's I/O classes.

Simple object-oriented semantics
Classes, instances, and modules are all implemented using the same simple concept of a namespace or mapping between variable names and values. Syntax and behavior of all three are similar, and are only a short step from the behavior of any Python dictionary. This consistency makes the behavior of Python programs extremely easy to predict, with nearly no special cases or exceptions to be memorized.

Operator overloading
Python allows you to easily overload all operators and many built-in functions to work as desired on user-defined classes. This allows your classes to interoperate cleanly with built-in types, and can also result in clearer code.

Dynamic dispatch and polymorphism
Both Python and Java have dynamic dispatch, meaning that the class whose code is evaluated from a line such as instance.method( ) is determined at runtime based on the class to which that instance belongs. Unlike Java, Python does not test for the existence of method( ) in any particular class at compile time. This is a corollary of dynamic typing, and has many of the same strengths and weaknesses. However, the flexibility it gives you over Java is significant, removing the need for Java-style interfaces and more generally promoting code reuse by making it easier for new code to interact with existing code.

No compile phase
The Jython development cycle does not have a separate compilation phase. Files are compiled if needed during execution, speeding up development.

First-class functions and classes
A first-class object can be returned from or passed to a function. In Python, functions, classes, and modules are all first-class objects. Being able to pass these kinds of code objects around can lead to very elegant code designs and increase reuse by allowing classes to "plug" functionality into existing structures. While some of this is technically achievable in Java using either anonymous inner classes or the java.lang.reflect package, the Python version is much easier to use. The following two code blocks are roughly equivalent, each creating a function object called someFunc and calling it.


import java.lang.reflect.*;
Class aClass = anInstance.getClass(  );
Method someFunc = aClass.getMethod("method", new Class[] {Integer, String});
someFunc.invoke(anInstance, new Object[] {new Integer(3), "Fred"});

someFunc = anInstance.method
someFunc(3, "Fred")
Extensive included library
Jython includes most of the Python standard library. Although some of that functionality is duplicated in the Java standard library, much of it is not. Examples include regular expression support (finally coming in JDK 1.4), parsers, network support, unit test frameworks, and much more.

All this additional functionality comes without having to sacrifice integration with existing Java code. Jython code can be compiled to Java .class or .jar files, and these files can be distributed like any other compiled Java files--the fact that the code was written in Jython can be made completely transparent to the end user.

Page 3 of 4

This article was originally published on March 25, 2003

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date