Jython Tips for Python Programmers
By Noel Rappin, Co-Author of Jython Essentials
04/11/2002
In my first article about Jython, I discussed the features of the Python scripting language and its Jython implementation that would be of greatest interest to Java programmers. Jython is a complete implementation of the Python programming language written in 100 percent pure Java, and allows easy Access to java libraries.
However, if you are already a Python programmer, then you know about the features of the Python programming language. For somebody already familiar with Python, the greatest attraction of using Jython is the ability to use any of the wide range of existing Java libraries and Tools While Being Able To Still Use Python as The Programming Language.
Jython Does Its Best to Shield a Python Programmmer from the details of java, but you'll STILL NEED TO KNOW Some of Those Details To Use Java Objects and Libraries Most Effectively from Jython.
This article contains 10 tips for using Java objects in Jython. I'll try not to assume much prior knowledge of Java, but space limitations prevent me from defining all Java terms in detail. Also, in this article when I need to differentiate the standard CPEMENTATION OF PYTHON, I'll Refer to It as CPYTHON.
IMPORTING JAVA PACKAGES
A Java package is a collection of Java classes which are typically stored in the same directory, one class to a file. Just like Python modules, Java packages must be imported to Jython before use. In order to be imported, a Java package must be In Either the Java ClassPath or the python pythonpath.
Java packages are imported as though they were Python modules, using the ordinary import statement You use the fully qualified name of the module for import To import the java.lang and java.util packages, you would type:.. Import java.lang
Import java.util
Unlike CPython, in Jython You Don't Have to Explicitly Specify Sub-packages. If you type the line:
Import Java
In Jython, Both java.lang and java.util (and all the other sub-packages of java) Are All Available. This Also Works for Standard Python Modules - In Jython, IF You Import Os, Then THE OS.PATH MODULE IS Automatically imported.
Often, Jython programmers leave the full name of the Java package in the code, to emphasize the creation of Java objects However, if you find that repetitive you can use the as clause to shorten the package name, commonly done like this.:
Import java.lang as lang
Import Java.util As Util
It's recommented that you not use the from version import statement:
From java import *
In Production Jython Code, Because of The Overhead of Importing All of The Standard Libraries, And Other Potential Problems. in General, It's A Good Idea To Stick To Import for Java Packages.
2. CREANG JAVA OBJECTS
Once Imported, Java Objects Are Created Using The Same Syntax As Ordinary Python Objects.
X = java.lang.string ()
z = java.util.hashmap ()
Internally, Jython calls the appropriate Java constructor for the class given the number and type of arguments (see Tip 6 below for details) - so the first line above calls the no-argument constructor for java.lang.String, but the line:
x = java.lang.string ("hi")
calls the one-argument constructor that expects a String. In other words, Jython is managing Java type information, so that you do not have to.When creating Java objects (and only when creating Java objects), you can pass keyword arguments to The Jython Construction That Are Not Part of the Type Signature of Any Java Construction for That Object. for example:
Win = javax.swing.jframe (size = (200,200))
For Each Keyword Argument X, Jython Looks for a Matching Public Method Of The Class SetX, And Calls That Method Automatic. If the is no such set method, Jython raises an error.
Related recaps
Jython Essentials
By Samuele Pedroni, NOEL RAPPIN
Table of contents
Index
Sample chapter
3. USING Objects in Python Statements
Once Created, Java Objects Can Be Used in Jython Statements, and Will Nearly Always Behave As Though They Were Native Python Objects (Some Restrictions Are listed Below).
Java objects can be used as the test in an if or while statement The following Java object values are equivalent to Python false -. Java.lang.Boolean FALSE, Boolean false, empty instances of java.util.Vector or java.util. Hashtable, and any empty class implementing the interfaces java.util.Dictionary, java.util.List, java.util.Map, or java.util.Collection. Note that unlike CPython, empty instances of Java strings are equivalent to Python true ( EMPTY PYTHON STRINGS Are Still False.
Any item of type java.util.Vector, java.util.enumeration, java.util.list, or java.util.itrator can be used as the list expression in A Jython for Statement. In Additional, you can use standard Python Index Notation (Such AS X [3]) for any subclass or import of java.util.Vector, java.util.dictionary, java.util.list, or java.util.map. However, SLICE Access (SUCH AS X [3 : 5]) IS Not Supported on Java Objects.Any Subclass of Java.lang.Exception Can Be Raised and Caught from Withnin Jython Using The Normal Python Try And Raise Statements.
Jython Tips for Python Programmers
Pages: 1, 2
4. Accessing Methods and FIELDS
Normally from Jython You Call Any Java Method OR Field Designated AS PUBLIC in The Java Class. You can get at private methods by changing Jython's Start-Up Options.
Jython Also Allows You To Avoid The Ubiquitous Java Get / Set Methods, Allowing Your Program To Have A More Pythonic Style. When Jython Sees a line of code such as:
x = javaobj.attribute
A Java Call of The Method Javaobj.getaTRibute (), IF Such A Method Exists, IS Automatic Or Generated. Similarly, An Assignment To Javaobj.attribute Is Converted To a call to javaobj.setttribute.
5. CREANG JAVA ARRAYS
Frequently, you will need to call a Java method that requires a Java array as an argument. Under normal circumstances, Jython will automatically convert a Python list or tuple to an array of the appropriate type when needed. This assumes that each item in the list Or Tuple CAN Be Converted to the appropriate Type - INT, Jython Will Raise a Runtime Error. So the Jython List [1, 2, 3] Can Be Converted to a Java Int [], long [], java.lang. Integer [], or java.lang.object [] as needed (but not, for example, to a java.lang.string []).
However, that conversion creates a copy of the list, and in some cases that's not what you want. For example, if the method you are calling changes the list in-place, the change will not propagate back to the Jython code, since the Array Is Only a Copy of The Jython List. Jython Provides The Jarray Module To Simplify The Direct Creation of Java Arrays When Needed.You Create Blank Arrays with The Zeros Method.
>>> IMPORT JARRAY
>>> Jarray.zeros (5, 'I')
Array ([0, 0, 0, 0, 0], Int)
...
>>> Jarray.Zeros (4, Java.lang.String)
Array ([None, None, None, None], java.lang.string
You can create arrays Directly from python sequences, by using the array method.
>>> Jarray.Array ([8, 9, 2, 1], 'I')
Array ([8, 9, 2, 1], INT)
Now, The First Argument is a python sequence, and the second is still the class or type signature.
6. Overloaded Methods
In The Case WHERE The Java Method Is Overloaded and Has More Tan One Definition, Jython Will Attempt To Match The Call To The Correct Method Based on The Number And Runtime Type of The Arguments.
Although the details can get complex, the basic idea is simple: Jython first attempts to choose a method with the same number of arguments as the call, and if there is more than one, it chooses the method whose required type is most similar to the Calling Object. in General, Jython Prefers Methods with Basic Java Types over Methods with Java Object Types.
7. Subclassing Java Objects
A Jython Object Can Be Declared Asia Subclass of a Java Object by Using The Standard Python SYNTAX:
Class JythonString (java.lang.string): Pass
Java interfaces can also be implemented in this way Jython does not do a compile-time check to determine if all methods in an interface are actually defined -. Calling an undefined method will raise a runtime exception.
Although Jython does have multiple inheritance, there is one limitation concerning Java objects. A Jython class can have at most one Java ancestor. This is true whether the ancestor is a direct parent, or an indirect parent via another Jython class.
Java subclasses behave differently when constructed. If a Jython class has a Java parent, and that parent has a no-argument constructor, that constructor is automatically called at the end of the Jython class' __init__ method, or before a Java attribute is used within that __init__ method. This is different from the normal Python behavior, where a parent class constructor is never called automatically. This is done to ensure that the Java objects are properly initialized before use.
8. Adding Attributes
Unlike ordinary Python objects, you can not create new attributes in a Java object instance simply by assigning to it - the instance must have been declared in Java Attempting to assign to an instance of a Java class that does not exist will raise an error..
>>> x = java.util.arrayList ()
>>> x.language = 'english'
TRACEBACK (InnerMost Last):
File "console", line 1, in?
Typeerror: Can't set Arbitrary Attribute in Java Instance: Language
To Work Around This Limitation, you can create a subclass of the java class - it can be an escher subclass. You can the Subclass:
>>> Class NewarrayList (java.util.arraylist):
... Pass ...
>>> x = newarraylist ()
>>> x.language = 'english'
>>> x.language
'english'
9. Serialization
Java objects can not be serialized using the standard Python pickle and cPickle modules. Both Java and Jython objects can be serialized using normal Java serialization. However, when deserializing a Jython object you can not use the normal java.io.ObjectInputStream class, you must use the Jython-Specific Org.Python.util.PythonObjectInputStream, AS Shown Here:
Import java.io as io
Import Org.Python.util As Util
Class testClass (IO.Serializable):
DEF __INIT_ _ (Self, Value = 0):
Self.Value = Value
SELF.MESSAGE = "Serialized"
Def toString (Self):
Return "Message:% (Message) s Value:
IS% (Value) S "% Self .__ DICT_ _
Instance = TestClass (3)
Outfile = IO.FileOutputStream ("Test.ser")
Outstream = IO.ObjectOutputStream (Outfile)
Outstream.writeObject (Instance)
Outfile.close ()
Infile = IO.fileInputStream ("Test.ser")
Instream = Util.PythonObjectInputStream (Infile)
ReadInstance = Instream.readObject ()
Print ReadInstance.toString ()
Message: Serialized Value: IS 3
If you do not use the PythonObjectInputStream, you will get a runtime error because the ordinary Java ObjectInputStream has difficulty finding and recreating the dynamically loaded proxy classes used for Jython's Java inheritance.
10. Special Bonus Differences
Finally, Here Are A Few of the Most Differences Between Jython and CPython, Not Directly Related To Object Usage:
All Jython Strings Arene Unicode Based, Therefore All Distinctions Between Regular and Unicode Strings That Exist In CPYTHON Are Ignored in Jython.
Since some Python keywords are common Java methods (like print), Jython is more flexible than CPython about allowing keywords as identifiers in places where the meaning is unambiguous (such as after a '.'). Jython uses Java garbage collection, not Cpython- STYLE REFERENCE Counting for Memory Management.
Jython Does Not Recognize The -o Optimization Flag.
Jython file objects are missing some of the functionality of their CPython equivalents, due to missing features in the JVM. Similarly, some CPython modules, most notably, os, sys, and socket, are missing functionality.
CPYTHON LIBRARIES WRITTEN IN C May Not Have Been Ported to Jython, And May Not Be usable (for example, tkinter).
For more information on jython, See the main jython site at
Http://www.jython.org, and get a copy of our Recent Book, Jython Essentials.
Noel Rappin Has Extensive Production Experience In Both Java and Python.