Introduction to Jython

Java and Python — each have their advantages and disadvantages. What is a programmer to do if he wants ease, efficiency, and power? Believe it or not, there is a solution — a way to merge both languages and get the best of both worlds. Read on to find out how it works.

Java is a very powerful language. Python is a very easy and very efficient language. Isn’t it a pity that  both of these languages remain separate? Or do they? Let me introduce Jython, a technology capable of merging Python and Java together to create efficient and powerful applications.

Jython is an implementation of Python in Java. With it, you can embed Python directly into your Java applets and applications, or you can use Java classes in Python, along with the modules of the standard library that Jython supports (at the time of writing this, the number of supported modules is a bit limited).

The source of Jython is also freely availible, just like Python’s source.

{mospagebreak title=Installing Jython}

Jython may be obtained from the Jython website:

http://www.jython.org

Currectly, the latest version is Jython 2.1. Download it and then move to the directory where it is installed. Next, open the file with your Java interpreter. For example:

java jython-21

The installation program will be presented to you, and installing it from there should be pretty straightforward. If you’re using Jython 2.1 in conjunction with Java 1.4 or later, be sure to include the source in your installation. Move to the directory where you installed Jython and open up “org/python/core/Py.java” in your favorite text editor. Replace every appearance of “assert” with “a_ssert” and ever appearance of “enum” with “e_num”. Do the same with “org/python/compiler/CodeCompiler.java” and “org/python/parser/PythonGrammar.java”. Note that the latter will require you to replace “e_numeration” to “Enumeration” when you are done. Jython 2.1 uses the two terms, which were set as keywords in Java 1.4.

Once you’re done, move to the directory where you installed Jython and start up the Jython interactive interpreter:

jython

If everything has gone correctly, you should see something that looks a lot like the Python interactive interpreter. Let’s test it out by executing some Python code:

>>> print ‘Hello World!’
Hello World!
>>> import math
>>> print math.sqrt ( 25 )
5.0
>>> someList = [ 5, 3, 4, 2 ]
>>> print someList [ 0 ]
5
>>> print math
(module ‘math’ (built-in))

As you can see, things work exactly the same as they do in Python.

{mospagebreak title=Calling Java Classes}

As I mentioned earlier, it is possible to call Java classes in Jython, which makes Jython extremely powerful. Anything that can be done in Java can be done in Jython using Python’s easy syntax. Development time can also be significantly cut by accessing Java classes through Jython.

Let’s play around with Java a bit. Using Swing in Java, it is fairly easy to create a simple dialog bearing a short message:

import javax.swing.JOptionPane;
class testDialog {
   public static void main ( String[] args ) {
      javax.swing.JOptionPane.showMessageDialog ( null, “This is a test.” );
   }
}

Using Jython, however, we can cut the amount of characters involved quite a bit. Save the following script, and pass its filename to the Jython interpreter:

import javax.swing.JOptionPane
javax.swing.JOptionPane.showMessageDialog ( None, “This is a test.” )

As you can see, Python’s syntax is used, but we’re using a Java package. We don’t have to compile anything, either. This speeds up the development process quite a bit, since we don’t have to wait for the Java compiler each time we fix a small bug in our applications.

If you do not see the advantage to using Jython yet, let’s convert a larger application from Java to Jython. We’ll create a die roller in Java. The user will be able to specify how many sides the die has and select how many times he or she wishes to roll the die. The application will then generate random values within the appropriate ranges and present the results to the user.

import java.util.Random;
import javax.swing.JOptionPane;
class DieRoller {
   public static void main ( String[] args ) {
      System.out.println ( “Die Roller” );
      System.out.println ( “- – - – -” );
      query();
   }
   public static void query () {
      String sidesS = JOptionPane.showInputDialog ( null, “How many sides should the die have?” );
      String rollsS = JOptionPane.showInputDialog ( null, “How many times should we roll the die?” );
      try {
          int sides = Integer.parseInt ( sidesS );
          int rolls = Integer.parseInt ( rollsS );
          roll( sides, rolls );
      } catch ( Exception e ) {
          JOptionPane.showMessageDialog ( null, “Error!” );
      }
   }
   public static void roll( int sides, int rolls ) {
      int current = 1;
      Random rand = new java.util.Random();
      while ( current <= rolls ) {
         System.out.println ( “Roll ” + current + “: ” + rand.nextInt ( sides ) );
         current++;
      }
   }
}

Using Jython, we can reduce the number of lines in the application while accomplishing the same exact product:

import java.util.Random;
import javax.swing.JOptionPane;
print ‘Die Roller’
print ‘- – - – -’
try:
   sides = int ( javax.swing.JOptionPane.showInputDialog ( None, ‘How many sides should the die have?’ ) )
   rolls = int ( javax.swing.JOptionPane.showInputDialog ( None, ‘How many times should we roll the die?’ ) )
   rand = java.util.Random()
   for current in range ( rolls ):
      print ‘Roll ‘ + str ( current + 1 ) + ‘: ‘ + str ( rand.nextInt ( sides ) )
except:
   javax.swing.JOptionPane.showMessageDialog ( None, ‘Error!’ )

Notice how we replace the while loop with Python’s for loop, which is more appropriate in this situation. In my opinion, the ability to use Python’s for loop is a major advantage with Jython.

Of course, you are not restricted to building applications with Java. You can build servlets, beans and applets, too. Let’s build a simple applet in Java to work with:

import java.applet.Applet;
class TestApplet {
   public void paint ( Graphics g ) {
      g.drawSring ( “A script a day keeps the doctor away.”, 5, 5 );
   }
}

Converting the application to Jython is very easy, and, again, we are left with the same product:

import java.applet.Applet;
class TestApplet ( java.applet.Applet ):
   def paint ( self, g ):
      g.drawString ( “A script a day keeps the doctor away.”, 5, 5 )

Of course, we’ll need to compile the applet before we can use it. This can be easily done:

jythonc –-deep –-core –-compiler <compiler path> TestApplet.py

Compiling an application is just as easy.

It’s also very possible and very simple to subclass an existing Java class. Subclassing a Java class is done in exactly the same way as subclassing a Python class. Let’s modify the nextInt method of java.util.Random to return a string rather than an integer. To do the random number generation, we’ll call the superclass’s method:

>>> import java.util.Random
>>> class StringRandom ( java.util.Random ):
…    def nextInt ( self ):
…       return str ( java.util.Random.nextInt ( self ) )

>>> x = StringRandom()
>>> x.nextInt()
’834361961′
>>> x.nextInt()
’159629831′
>>> x.nextInt()
‘-1197591800′

Since adding an attribute to an existing Java object is not possible in Jython, you are forced to create a subclass in Jython if you wish to add additional attributes:

>>> import java.util.Random
>>> rand = java.util.Random()
>>> rand.doesNotExist = 5
Traceback (innermost last):
  File “<console>”, line 1, in ?
TypeError: can’t set arbitrary attribute in java instance: doesNotExist
>>> class DumbyRandom ( java.utilRandom ):
…    pass

>>> rand = DumbyRandom()
>>> rand.doesNotExist = 5
>>> print rand.doesNotExist
5
>>> print rand.nextInt()
-1884599813

As you can see, the DumbyRandom class functions exactly the same as the Random class, except for the fact that we can add attributes to objects created from it.

{mospagebreak title=Embedding}

Jython allows us to embed Python code in Java code easily, and there are several approaches to it. The first is to use the PythonInterpreter object to execute Python code contained in a separate file. Let’s create a Python file called “testCode.py” with the following code inside of it:

import math
print ‘Hello Jython World!’
print math.pi
print math.e
print math.sqrt ( 25 )

Execuing it in Java is simple using the execfile method:

import org.python.util.PythonInterpreter;
import org.python.core.*;
class TestPython {
   public static void main ( String[] args ) {
      try {
         org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
         python.execfile ( “testCode.py” );
      } catch ( Exception e ) {
         System.out.println ( “An error was encountered.” );
      }
   }
}

We can also place code within the Java application itself using the exec method. Let’s recreate our first example with the Python code included in the Java application rather than an external file:

import org.python.util.PythonInterpreter;
import org.python.core.*;
class TestPythonTwo {
   public static void main ( String[] args ) {
      try {
         org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
         python.exec ( “import math” );
         python.exec ( “print ‘Hello Jython World!’” );
         python.exec ( “print math.pi” );
         python.exec ( “print math.e” );
         python.exec ( “print math.sqrt ( 25 )” );
      } catch ( Exception e ) {
         System.out.println ( “An error was encountered.” );
      }
   }
}


We can also get and set variables in the local namespace by using the get and set methods. This allows us to interact with Python a bit more, which is our goal when embedding Python code inside Java applications:

import org.python.util.PythonInterpreter;
import org.python.core.*;
class TestPythonTwo {
   public static void main ( String[] args ) {
      try {
         org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
         python.exec ( “import math” );
         python.exec ( “print ‘Hello Jython World!’” );
         python.exec ( “print math.pi” );
         python.exec ( “print math.e” );
         python.set ( “ourSetVariable”, new org.python.core.PyInteger ( 25 ) );
         python.exec ( “ourSetVariable = math.sqrt ( ourSetVariable )” );
         org.python.core.PyObject ourSetVariable = python.get ( “ourSetVariable” );
         python.exec ( “print ” + ourSetVariable );
      } catch ( Exception e ) {
         System.out.println ( “An error was encountered.” );
      }
   }
}

Conclusion

Jython is an extremely powerful tool for development in both Python and Java. It allows you to use Python to call Java classes, increasing the power of Python, and it allows you to execute Python code inside Java applications by using the exec and execfile methods. Jython also allows you to subclass Java classes using Python. Jython can significantly decrease the effort needed to produce a powerful application, or even an applet, servlet or bean.

Of course, this article only covers the tip of the iceburg (forgive the cliché!). There is a lot more to Jython, but it would take a very lengthy article to cover all of it. It’s up to you to explore more of Jython. Good luck!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan