Introduction To Jython
Introduction To Jython
Table of Contents
If you're viewing this document online, you can click any of the topics below to link directly to that section.
This tutorial covers Jython in progressive detail. In this first half of the tutorial, we'll
cover the concepts and programming basics of working with Jython, including access
options and file compilation, syntax and data types, program structure, procedural
statements, and functions. The second half of the tutorial will start with a conceptual
introduction to object-oriented programming in Jython. From there, we'll move on to a
more hands-on discussion, encompassing class statements, attributes, and methods,
abstract classes, and operator overloading. This advanced discussion will also include
debugging, string processing, file I/O, and Java support in Jython. The tutorial will
conclude with a step-by-step demonstration of how to build a working GUI app in
Jython.
The example code will be very simple in the beginning of the tutorial, but by the end of
the second half you will be up and running with complete functions, classes, and
programs. Included with the tutorial is a set of appendices detailing the inner workings
of Jython.
Part 1
Part 2
To benefit from the discussion, you should be familiar with at least one procedural
programming language and the basic concepts of computer programming, including
command-line processing. To fully utilize Jython's features you should also be familiar
with the basic concepts of object-oriented programming. It will also be helpful to have a
working knowledge of the Java platform, as Jython runs on a JVM; although this is not
a requirement of the tutorial.
Note that this tutorial is oriented towards Windows systems. All command examples
will employ Windows syntax. In most cases similar commands perform the same
functions on UNIX systems, although these commands will not be demonstrated.
To use Jython you must also have a Java Runtime Environment (JRE) installed on
your system. It is recommended that you use the latest JRE available (1.4.2 at the time
of writing), but any version at or beyond Java 1.2 should work fine. If you are going to
use Jython from a browser (that is, as an applet), you must have at least a JRE 1.1
available to the browser. See Resources and feedback on page 66 to download the
All code examples in this tutorial have been tested on Jython running on the Sun Java
1.4.1 JRE on Windows 2000. Examples should work without change on any similar
configuration on other operating systems.
Acknowledgements
I would like to acknowledge Mike Squillace and Roy Feigel for their excellent technical
reviews of this tutorial.
Installation instructions
In this section we'll walk through each of the steps for downloading, installing, and
verifying Jython on your development system.
Download Jython
You can download Jython 2.1 from the Jython home page. You'll find easy-to-follow
download instructions on the download page.
As previously mentioned, this tutorial is based on the current stable Jython level, which
is version 2.1. More advanced development levels may also be available from the
Jython home page.
Install Jython
Installing Jython is simple: just execute the class file you've downloaded from the
Jython homepage. Assuming that you have a JRE installed and have the downloaded
class file in your current directory (C:\ in the examples below) the following command
will install Jython (note that <java_home> is the directory the JRE is installed in):
C:\><java_home>\bin\java jython-21
Please follow the install application's prompts. I recommend you select the defaults,
and that you select c:\Jython-2.1 as the destination directory.
C:\>dir c:\Jython-2.1
Directory of C:\Jython-2.1
A test run
The final step is to ensure that Jython is configured. To run Jython, start by entering the
command:
C:\>c:\jython-2.1\jython
Finally, we'll exit Jython. At the Jython prompt, enter the following command:
What is Jython?
As previously mentioned, Jython is an implementation of Python written in the Java
language and integrated with the Java platform. Python is a scripting language often
used in UNIX-based systems, including Linux. Python was invented by Guido van
Rossum and introduced to the developer community in 1991. Jython currently supports
the Python syntax at level 2.1.
In general, it can be said that scripting languages value programmer efficiency over
machine efficiency and performance. Compared to a programming language such as
the Java language, Jython is easy to learn and efficient to code.
Jython can also be described as an agile language. Agile languages are generally
thought of as being capable of performing a wide variety of tasks and useful for many
different types of problems, easy-to-use and yet powerful and expressive. They are
also ideal rapid prototyping languages.
Advantages of Jython
Like its C-based cousin Python, Jython is most at home when used to develop small
programs and scripts; it has many features that allow simple but functional programs to
be created in a few minutes. This does not mean Jython cannot be used for large-scale
programming. In fact, Jython supports a sophisticated packaging scheme, similar to
that of the Java language. By virtue of its object-oriented nature, Jython is highly
extendable and provides the latest constructs for effective software engineering.
Like the Java language and unlike some other scripting languages such as Perl and
Rexx, Jython was designed to be an object-oriented language from the start. Thus, it
offers powerful object-oriented programming (OOP) features that are easy to
understand and use.
One of Jython's biggest advantages is that it runs on any JVM, so applications coded in
Jython can run on almost any computing system.
@echo off
rem This file generated by Jython installer
rem
JAVA_HOME=<java_home>
rem
rem collect all arguments into %ARGS%
set ARGS=
:loop
if [%1] == [] goto end
set ARGS=%ARGS% %1
shift
goto loop
:end
%JAVA_HOME%\bin\java.exe
-Dpython.home=C:\jython-2.1
-cp "C:\jython-2.1\jython.jar;%CLASSPATH%"
org.python.util.jython %ARGS%
Everything is interpreted
At its heart Jython is an interpreted language. In Jython, there is no pre-compile step
as there is in Java and C++; each time Jython code is run it is interpreted afresh. As
such, code changes can be very quickly made and tested. Jython code can also be
entered interactively (that is, one line at a time). Furthermore, you can dynamically
construct Jython code (that is, as a string) and execute it directly. This enables coding
flexibility not possible in Java coding.
The Jython interpreter converts Jython source into an internal form for more efficient
processing. It does this during a first pass that verifies syntax. Once this pass is
complete the internalized source is interpreted. Jython also caches this internalized
form on disk. In a Java class file for the Jython module <name>.py, the cached file
would be <name>$py.class.
Interpretation does have its disadvantages, although most are minor. For example, use
of an undefined variable is not a compiler error, so it will be detected only if (and when)
the statement in which the variable is used is executed. While this can seem a
disadvantage when compared to compiled languages, the fact that you can edit and
then immediately run a program and experience the error (if it exists) makes up for it. A
simple test-and-debug procedure takes about as much time as repeated edit-compile
steps do to remove an error.
About performance
Because Jython is interpreted, it can be slower than a compiled language such as
Java. In most applications, such as scripts or GUIs, this difference is hardly noticeable.
In most cases, Jython's increased design and coding flexibility more than makes up for
any small performance loss.
Because Jython code is dynamically converted to Java byte code, the latest
enhancements to the Java platform (such as JITs and Sun's HotSpot JVM) can also
eliminate many performance issues.
We'll start with a brief Jython interactive session. Enter the following commands after
the ">>>" or "..." prompts:
C:\>c:\jython-2.1\jython
You should receive output that looks something like this:
With this example you can see how input is immediately executed. This includes simple
expressions and more complex actions such as function definitions (that is, the fac
function). Defined values and functions are available for immediate use. Notice, also,
that Jython supports very large integers via the long type.
Note that in the above example the indentation of the fac function is critical. You'll
learn more about this requirement later in the tutorial (see Blocks on page 31 ).
If Jython accepted only command-line input it wouldn't be all that useful; thus, it also
accepts source files. Jython source files end in the extension .py. A Jython file must
contain a sequence of Jython statements. Expressions, such as 1 + 2, are not valid
statements (they execute but produce no displayed output).
To display expressions, you must place them in a print statement. Thus, the
sequence from the previous section could be coded in a source file as follows:
print 1 + 2
print "Hello" + "Goodbye"
def fac(x):
if x <= 1: return 1
return long(x) * fac(x-1)
print fac(3)
print fac(100)
The above code would produce the same output as the examples in Using Jython as a
command-line interpreter on page 11 . In fact, the statements could have been entered
interactively (with the addition of a blank line after the fac function) and would result in
the same output.
-- or --
The print statement above can also contain a list of expressions separated by
commas. Each such expression is output with a space automatically added between
them. So that print "Hello", "Goodbye" outputs Hello Goodbye.
If a print statement ends in comma, no new-line is output. The line print by itself
outputs a new-line.
Note that the .py extension is required; otherwise, a "file not found" error will occur. The
jython command has several options. See the Jython home page (in Resources and
feedback on page 66 ) for more information.
def fac(x):
if x <= 1: return 1
return long(x) * fac(x-1)
if __name__ == "__main__":
print 1 + 2
print "Hello" + "Goodbye"
print fac(3)
print fac(100)
Again, running this file results in the same output as before. But if the file were
imported into another program that only wanted to reuse the fac function, then none of
the statements under the if (see The if statement on page 48 ) test would be executed.
Note also that each module has a name; the one directly executed from the
command-line is called "__main__". This feature can be used to create a test case for
each module.
Compiled Jython
Jython source files can be compiled to Java source code (which is automatically
compiled into byte-code) to produce standalone class or Java Archive Files (JAR) files.
This step is necessary to create Jython code that is called directly from the Java
platform, such as when creating an applet or a servlet. It is also useful to provide
Jython applications without releasing the Jython source.
Jython can be compiled into a pure Java class that can run directly on any JVM by use
of the jythonc command (that is, assuming you have the necessary Jython JAR in
the Java CLASSPATH). For more details on using jythonc see the Jython home page
(Resources and feedback on page 66 ).
A compilation example
We'll use the factor.py file (see Resources and feedback on page 66 ) as our example
standalone program. To compile it, use the command:
c:\>c:\jython-2.1\jythonc factor.py
factor running...
For -1 result = Exception - only positive integers supported: -1
For 0 result = 1
For 1 result = 1
For 10 result = 3628800
For 100 result =
93326215443944152681699238856266700490715968264381621468592963895217599
99322991560894146397615651828625369792082722375825118521091686400000000
0000000000000000
For 1000 result = 4023872600770937735437024
... many digits removed ...
00000000000000000000
Note that the output is identical to that generated by using the factor.py program
directly.
Everything is an object
Unlike the Java language, Jython sees everything, including all data and code, as an
object. This means you can manipulate these objects using Jython code, making
reflective and functional programming very easy to do in Jython. See Appendix G:
Jython types summary on page 80 for more information.
Some select types, such as numbers and strings, are more conveniently considered as
values, not objects. Jython supports this notion as well.
Jython supports only one null value, with the reserved name of None.
Common operators
All Jython data types support the following fundamental operations:
object as y; else 0
x is not y Distinctness Returns 1 if x is not the same
object as y; else 0
Note that unlike in the Java language, all types are comparable. In general, if the types
of the operands do not match, the result is unequal. The less-than or greater-than
relations on complex types are consistent but arbitrary.
Boolean types
Jython has no separate boolean type. All the other types described in the following
sections can be used as booleans. For numeric types, zero is considered to be false
and all other values true. For structured types (that is, sequences and maps), an empty
structure is considered to be false and others true. The None value is always false.
Numeric types
Numbers are immutable (that is, unchangeable after creation) objects treated as
values. Jython supports three numeric types, as follows:
• Long: large values limited only by the JVM's available memory (like Java
BigIntegers).
• Floating point values may have fractional parts. Floats support values identical to
the Java double type.
• Complex values are a pair of floating point values, called the real and imaginary
part. If x is a complex value, then x.real is the real part and x.imag is the
imaginary part. Either part may be 0.0. The method x.conjugate produces a new
Operation/Function Usage
-x Negate x (that is, 0 - x)
+x Posate - no change (that is, 0 + x)
x + y Add y to x
x - y Subtract y from x
x * y Multiply x by y
x / y Divide x by y
x % y Take modulus of x by y
divmod(x, y) Return (x / y, x % y)
x ** y Raise x to the y power
pow(x, y) Raise x to the y power
abs(x) If x < 0, then -x; else x
int(x) Convert x to an integer
long(x) Convert x to a long
float(x) Convert x to a float
complex(r, i) Convert r and i to a complex
complex(x) Convert x to a complex
Note: For numeric types, the operands are promoted to the next higher type. For
integer operands /, %, and ** result in integer results. For the int, long, float, and
complex conversion functions, x may be a string or any number.
Function Comment(s)
ceil(v) Computes the ceiling and floor of v.
floor(v)
sin(v) Computes the sine, cosine, and tangent of v.
cos(v)
tan(v)
acos(v) Computes the arcsine, arccosine, and arctangent of v (or v /
w).
asin(v)
atan(v)
atan2(v, w)
sinh(v) Computes the hyperbolic sine, cosine, and tangent of v.
cosh(v)
tanh(v)
exp(v) Computes the powers and logarithms of v.
pow(v, w)
sqrt(v)
log(v)
log10(v)
fabs(v) Computes the absolute value of v.
fmod(v, w) Computes the modulus of v and w. May not be the same as
v % w.
modf(v) Returns (as the tuple (i, f)) the integer and fractional parts of
v (both as floats).
frexp(v) Returns (as the tuple (m, e)) the float mantissa and integer
exponent of v. The result is such that v == m * 2 ** e.
ldexp(v, w) Computes v * 2 ** w (w must be an integer).
hypot(v, w) Computes the hypotenuse of v and w (that is, sqrt(v * v
+ w * w)).
PI = 3.141593, e = 2.718282
Sine of 0.500000 = 0.479426
Cosine of 0.500000 = 0.877583
Tangent of 0.500000 = 0.546302
Collection types
Frequently, you will need to create collections of other data items. Jython supports two
major collection types. The most basic is the sequence type which is an ordered
collection of items. Sequences support several subtypes such as strings, lists, and
tuples. The other is the map type. Maps support associative lookup via a key value.
You'll learn about both types in this section.
Sequence types
A sequence is an ordered collection of items. All sequences are zero-indexed, which
means the first element is element zero (0). Indices are consecutive (that is, 0, 1, 2, 3,
...) to the length (less one) of the sequence. Thus sequences are similar to C and Java
arrays.
A slice of life
The many valid forms of slicing are summarized below. Assume x is a sequence
containing 10 elements (indexes 0 through 9).
Sequence operators
Jython supports several operations between sequences (x and y), as summarized
below:
Sequence functions
Strings
A string is an immutable sequence of characters treated as a value. As such, strings
support all of the immutable sequence functions and operators that result in a new
string. For example, "abcdef"[1:4] is the new string "bcd". For more information
on string functions see Appendix B: String methods on page 68 .
Jython does not have a character type. Characters are represented by strings of length
one (that is, one character).
Strings literals are defined by the use of single or triple quoting. Strings defined using
single quotes cannot span lines while strings using triple quotes can. A string may be
enclosed in double quotes (") or single ones ('). A quoting character may contain the
other quoting character un-escaped or the quoting character escaped (proceeded by
the backslash (\) character). See Appendix A: Escape characters on page 68 for more on
this.
String examples
Following are some example strings:
• "This is a string"
• 'This is also a string'
• "This is Barry's string"
• 'Barry wrote "Introduction to Jython"!'
• "This is an escaped quote (\") in a quoted string"
• r"\s*xyx\s*" - equivalent to"\\s*xyx\\s"
• u"the number one is \u0031" (vs. "the number one is \x31")
Note that the next-to-last example shows a raw string. In raw strings the backslash
characters are taken literally (that is, there is no need to double the backslash to get a
backslash character). This raw form is especially useful for strings rich in escapes,
such as regular expressions. We'll talk more about regular expressions in Part 2 of this
tutorial.
The last example shows a Unicode string and how to create Unicode escaped values.
Note that all strings are stored using Unicode character values (as provided by the
JVM); this format just lets you enter Unicode character values.
"This string uses ' and " 'that string uses ".'
becomes this string:
While this is a short mixed-quote string: '''This string uses ' and that
string uses ".'''
%{(key)}{width}{.precision}x
For example
prints
Tuples
Tuples are immutable lists of any type. Once created they cannot be changed. Tuples
can be of any length and can contain any type of object. Some examples are shown
here:
Example Comment(s)
() An empty tuple
(1,) A tuple with one element, an integer;
the comma is needed to distinguish the
tuple from an expression like (1)
(1, 'abc', 2, "def") A tuple with four elements, two integers
and two strings
((), (1,), (1,2), (1,2,3)) A tuple of tuples; Each sub-list contains
integers
(1, "hello", ['a','b','c'], A mixed tuple of integers, strings and a
"goodbye") sub-list of strings
v1 = 1; v2 = 10 A tuple of integers; variable references
and expressions are supported
(1, v1, v2, v1 + v2)
Note that although a tuple is immutable, the elements in it may not be. In particular,
nested lists (see Lists on page 26 ) and maps (see
Maps and dictionaries on page 27 ) can
be changed.
Ranges
To implement iteration (see the The for statement on page 51 ) Jython uses immutable
sequences of increasing integers. These sequences are called ranges. Ranges are
easily created by two built-in functions:
Ranges run from start (defaults to 0), up to but not including end, stepping by inc
(defaults to 1). For example:
Lists
Lists are mutable sequences of any type. They can grow or shrink in length and
elements in the list can be replaced or removed. Lists can be of any length and can
contain any type of object. For more information on list functions see Appendix C: List
methods on page 71 . Some examples are shown below.
Example Comment(s)
[] An empty list
[1] A list with one element, an integer
[1, 'abc', 2, "def"] A list with four elements, two integers
and two strings
[[],[1],[1,2],[1,2,3]] A list of lists; Each sub-list contains
integers
[1, "hello", ['a','b','c'], A mixed list of integers, strings and a
"goodbye"] sub-list of strings
v1 = 1; v2 = 10 A list of integers; variable references
and expressions are supported
[1, v1, v2, v1 + v2]
l.append(6) # l is [1,2,3,4,5,6]
w = l.pop() # w is 6, l is [1,2,3,4,5]
x = l.pop(-1) # x is 5, l is [1,2,3,4]
y = l.pop(0) # y is 1, l is [2,3,4]
z = l.pop(0) # z is 2, l is [3,4]
List comprehensions
Lists can also be created via an advanced notation, called list comprehensions. List
comprehensions are lists combined with for and if statements to create the elements
of the list. For more information see The for statement on page 51 andThe if statement
on page 48 . Some example list comprehensions follow:
Maps support associative lookup via the key value. A key can be any immutable type.
Keys must be immutable as they are hashed (see Appendix E: Built-in functions on
page 72 ) and the hash value must stay stable. Common key types are numbers, strings,
and tuples with immutable elements. Values may be of any type (including None). If m
is a map, function len(m) returns the number of items in the map.
Maps, like sequences, support subscripting, but by key instead of index. For example,
if m is a map, x = m["x"] gets a value from the map and m["x"] = x adds a new
value to or replaces a value in the map.
Example dictionaries
Some example dictionary literals are below:
Example Comment(s)
{} An empty dictionary
{1:"one", 2:"two", 3:"three"} A dictionary with three elements that
map integers to names
{"one":1, "two":2, "three":3} A dictionary with three elements that
map names to integers
{"first':'Barry", "mi":"A", A dictionary that maps a name
"last":"Feigenbaum"}
{"init":(1,2,3), A dictionary containing a tuple, a list,
"term":['x','y','z'], and another dictionary
"data":{1:10,2:100.5}}
t = (1,2,3); l = A dictionary containing a tuple, a list,
['x','y','z']; d = and another dictionary; variable
{1:10,2:100.5} references and expressions are
supported
{"init":t, "term":l,
"data":d}
As shown in Formatting strings and values on page 24 , dictionaries are convenient for
format mapping.
File structure
As explained in the introduction, Jython programs are simply text files. These files
contain statements that are interpreted as they are input (after a quick parsing for
syntax errors). Other files can be effectively included into Jython programs by use of
the import (see Modules and packages on page 35 ) and exec statements (see
Dynamic code evaluation on page 32 ).
Commentary
Jython has two forms of comments:
• Remarks are comments introduced with the sharp (#) character. All text on the same
line after the sharp is ignored. Remarks can start in any column.
• Documentation comments are a string literal located immediately after the start of
an externalized block, such as a module, class, or function. The string does not
change the behavior of the block; yet the comment can be accessed via the special
attribute __doc__ to create descriptions of the block.
A commentary example
The following example shows a function (fac) that has a documentation comment and
two remarks. It also demonstrates how to access the documentation comment
programmatically.
def fac(x):
"The fac function computes the value x! (x factorial)"
if x <= 1: return 1 # base case
return long(x) * fac(x-1) # use recursion on reduced case
:
print fac.__doc__
Statement syntax
As you likely have gathered from the previous sections, Jython has a simple syntax. It
more closely resembles English than languages like C and Java language. In
particular, each source line is (generally) a single statement. Except for expression
and assignment statements, each statement is introduced by a keyword name, such
as if or for. You may have blank or remark lines between any statements.
You don't need to end each line with a semicolon but you may do so if desired. If you
wish to include multiple statements per line, then a semicolon is needed to separate
statements.
If required, statements may continue beyond one line. You may continue any line by
ending it with the backslash character, as shown below:
If you are in the middle of a structure enclosed in parenthesis (()), brackets ([]) or curly
braces ({}), you may continue the line after any comma in the structure without using a
backslash. Here's an example:
x = (1, 2, 3, "hello",
"goodbye", 4, 5, 6)
Note that names starting with underscore are generally reserved for internal or private
names.
Jython also has several reserved words (or keywords) which cannot be used as
variable, function, or class names. They fall under the following categories:
• Statement introducers: assert, break, class, continue, def, del, elif, else, except,
exec, finally, for, from, global, if, import, pass, print, raise, return, try, and while.
Note that keywords can be used in special circumstances, such as names of methods.
For instance, you might use a keyword to call a Java method with the same name as a
Jython keyword. Improper keyword use will generally cause a SyntaxError.
Blocks
Blocks (or suites) are groups of statements that are used where single statements are
expected. All statements that can take a block of statements as a target introduce the
block with the colon character. The following statements (or statement clauses) can
take a block as their target: if, elif, else, for, while, try, except, def, and class. Either a
single statement or small group of statements, separated by semicolons, may follow
the colon on the same line, or a block may follow the statement indented on
subsequent lines.
I highly recommend that you use spaces to indent. Using tabs can cause problems
when moving between systems (or editors) with different tab stops. Do not mix tabs
and spaces in the same source file. By convention, four spaces are used per level.
Note: All the lines in the outermost block of a module must start at column one;
otherwise, a SyntaxError is created.
Example blocks
Unlike with C and the Java language, in Jython curly braces are not used to delimit
blocks; indentation is used instead. For example
The block that is the body of the for-loop is indicated by the indented code. All lines in
the body (except for comments) must be indented to the same position. The same loop
could be written as:
• Built-in symbols defined by the Jython runtime are always available unless
redefined in another scope.
• Global variables are visible to the an entire module, including functions and classes
declared in the module. A dictionary of the variables in the current global scope can
be accessed via the globals function.
• Local function arguments and variables declared in a function body are visible to
that block. A dictionary of the variable names in the current local scope can be
accessed via the locals function. In a module and outside of any function, the local
and global scopes are the same.
In general, variables are visible in the scope of the block they are declared in and in
any function (see Jython functions on page 55 ) defined in that scope. Variables can be
declared only once per scope; subsequent use re-binds that variable. Unlike in C++
and the Java language, nested blocks inside functions do not start new scopes.
v1 = 100; v2 = 200
l1 = [1, 2, v1, v2]
d1 = {"simple":123, "complex":(v1, v2, l1)}
expr = raw_input("Enter an expression:")
print eval(expr) # evaluate and print the expression
Below are some sample expressions to evaluate using the code above and the results
of those evaluations:
All three forms optionally take two dictionaries that define the global and local
namespaces. See Visibility and scopes on page 32 for more details on namespaces. If
these dictionaries are omitted, the current local namespace (as provided by the
locals function) and the current global namespace (as provided by the globals
function) are used.
prints: 104.
More details on the use of the eval function and exec statement are available in the
Python Library Reference (see Resources and feedback on page 66 ).
Jython packages are conceptually hierarchically structured sets of modules. They are
implemented as directories that contain one or more modules and a special file,
__init__.py, that is executed before the first module of the package is executed.
Modules and packages enable reuse of the extensive standard Jython and Java
libraries. You can also create modules and packages for reuse in you own Jython
applications. For more information on the available Jython modules see Appendix F:
Jython library summary on page 76 . For more information on the available Java libraries
visit the Sun Microsystems' Java technology home page (in Resources and feedback
on page 66 ).
-- or --
-- or --
The module value names a Jython (.py) file or dotted-path to a Jython package. The
name value selects specific names from the module. Module names are case sensitive.
These arguments can be repeated. The optional alias value allows imported objects
to be renamed.
Example imports
Below are some example import statements:
Example Comment(s)
import sys Import the sys module. All names in
sys can be referenced by the prefix
sys.
from sys import exc_info Imports the exc_info function from
the sys module. No prefix is needed.
from sys import * Imports all the names and functions in
the sys module. No prefix is needed.
from sys import exc_info as Imports the exc_info function from
einfo the sys module and names it einfo.
No prefix is needed.
from string import uppercase Imports the uppercase and
as uc, lowercase as lc lowercase functions from module
string. No prefix is needed.
import sys, string Imports modules sys and string
import com.ibm.tools.compiler Imports the compiler module from
as compiler the com.ibm.tools package giving it
the short name compiler.
and python.prepath variables in the Jython registry to search for these files. You
can use any text editor to add to or update the registry file in the Jython home
directory (usually c:\jython-2.1). For more information, see the Jython registry (in
Resources and feedback on page 66 ) or the registry file itself.
By default, Jython will search the directory containing the executing source file; thus,
modules located in the same directory as the importing Jython program can be found.
Frequently the current directory is also on the path. Simply enter the following
command to examine the current search paths:
import sys
print sys.path
To find Java class files, Jython searches both the Java CLASSPATH and the sys.path
values.
Import is executable
Unlike in the Java language, the import statement is executable and is not a compiler
directive in Jython. Thus, imports do not need to be done at the start of a module; just
sometime before the imported symbols are used. In fact importing can be done
conditionally, as in the following example.
:
# lots of other stuff
:
if __name__ == "__main__":
:
from sys import exit
exit(0)
import sys
:
# lots of other stuff
:
del sys
Subsetting imports
When you import modules, all values assigned or functions created in the module are
usually available for reference by the module importer. You can prevent this by altering
the code within the module. Either start the name with an underscore (_) or define a
special variable, __all__, at the start of the module, listing only the names of the
variables or functions you want to be imported. For example, the __all__ definition
below:
__all__ = ["getline","clearcache","checkcache"]
A similar strategy can be used at the module directory level. Defining the variable
__all__ in a file called __init__.py instructs the interpreter as to which modules to
import from the package if the wildcard (*) is used in the import statement. For
instance, if the line __all__ = ['mod1', 'mod3', 'globals'] is in a file called
__init__.py in a directory named modules, it will cause the statement from
modules import * to import the modules mod1, mod3, and globals from the
modules directory.
import os
import sys
About exceptions
Regardless of how much care a programmer takes in designing and testing his or her
code, unexpected errors, or exceptions, can occur. Jython provides excellent support
for recovering from these errors,
• 1 Exception
• 1.1 SystemExit
• 1.2 StopIteration
• 1.3 StandardError
• 1.3.1 KeyboardInterrupt
• 1.3.2 ImportError
• 1.3.3 EnvironmentError
• 1.3.3.1 IOError
• 1.3.3.2 OSError
• 1.3.4 EOFError
• 1.3.5 RuntimeError
• 1.3.5.1 NotImplementedError
• 1.3.6 NameError
• 1.3.6.1 UnboundLocalError
• 1.3.7 AttributeError
• 1.3.8 SyntaxError
• 1.3.8.1 IndentationError
• 1.3.8.2 TabError
• 1.3.9 TypeError
• 1.3.10 AssertionError
• 1.3.11 LookupError
• 1.3.11.1 IndexError
• 1.3.11.2 KeyError
• 1.3.12 ArithmeticError
• 1.3.12.1 OverflowError
• 1.3.12.2 ZeroDivisionError
• 1.3.12.3 FloatingPointError
• 1.3.13 ValueError
• 1.3.14 ReferenceError
• 1.3.15 SystemError
• 1.3.16 MemoryError
• 2 Warning
• 2.1 UserWarning
• 2.2 DeprecationWarning
• 2.3 PendingDeprecationWarning
• 2.4 SyntaxWarning
• 2.5 OverflowWarning
• 2.6 RuntimeWarning
• 2.7 FutureWarning
This hierarchy is a subset of the Python Library Reference (see Resources and
feedback on page 66 ). These exceptions may be subclassed.
try: statement
except type, var: statement
:
else: statement
-- or --
try:
block
except type, var:
block
:
else:
block
The except clause may be repeated with different type values. If so, the exceptions
either must not overlap hierarchically (that is, be siblings) or they must be ordered from
child to root exceptions. The optional type value is an exception type (either a
subclass of exceptions.Exception or java.lang.Throwable). If type is
missing, then the except clause catches all Jython and Java exceptions. The optional
var value receives the actual exception object. If var is missing, then the exception
object is not directly accessible. The else clause is optional. It is executed only if no
exception occurs.
If an exception occurs in the try clause, the clause is exited and the first matching
except clause (if any) is entered. If no exception matches, the block containing the
try-except-else is exited and the exception is re-raised.
If an exception is raised in the except or else clause, the clause will exit and the new
exception will be processed in the containing block.
import sys
:
try:
:
except:
type, value, traceback = sys.exc_info()
More details on the exceptions and trace backs is available in the Python Reference
Manual (see Resources and feedback on page 66 ).
be executed once the try clause is entered, even if it is exited via a return statement
(see The return statement on page 57 ) or an exception. The try-finally statement
has the following forms:
try: statement
finally: statement
-- or --
try:
block
finally:
block
Exceptions are generated by called functions or built-in services. You can also
generate one by using the raise statement. The raise statement has the following
forms:
raise exception
-- or --
-- or --
raise
Example Comment(s)
raise Re-raise the current exception; used in
an except block to regenerate the
exception
raise IOError Create and raise an IOError with no
message
raise anIOError Re-raise an existing IOError object
raise IOError, "End of File" Create and raise an IOError with a
explanatory message
from java import io Create and raise a Java exception with
a explanatory message
raise io.IOException, "End of
File"
pass
performAction(1)
performAction(2)
performAction(3)
# below is the same as: "(0 <= x) and (x < 100)" but is more concise
0 <= x < 100 # tests a range
Operation Comment
( expression ) Nested expression or grouping
( expr1, ..., exprN ) Tuple constructor
[ expr1, ...,exprN ] List constructor
{ key1:value1, ..., Dictionary constructor
keyN:valueN }
repr (representation) expression
`expression`
x.name Member (attribute or method) selection
x[i], x[i:j], x[i:j:k] Subscripting or slicing
x(...) Function call
** Raise to power (right associative)
+ Posate
- Negate
~ Bit-wise not
* Times
/ Divide
% Modulo
+ Plus
- Minus
<<, >> Bit-wise shifts
& Bit-wise and
^ Bit-wise xor
| Bit-wise or
is, is not Sameness test
in, not in Containment test
<, <=, >, >=, ==, !=, <> Relational test
not Logical not
and Logical and
or Logical or
lambda Declare a lambda function
More than one variable can have a reference to the same object; this is called aliasing.
For this reason, Jython supports the is and is not operators to test whether or not
two variables refer to the same object.
A variable can only be declared once in a block. This means that it is declared (by the
parser) in the block even if the flow in the block does not execute the assignment
statement that creates it. The variables will have an undefined value until the first
assignment is actually executed.
Note that like the assignment statement other statements can bind variables. Some
examples are the class, def, for, and except statements.
Parallel assignment
The assignment statement supports sequence unpacking. This can achieve a form of
parallel assignment. For example, the following sets a to 1, b to 2, and c to 3:
(a, b, c) = (1, 2, 3)
-- or --
x = (1, 2, 3)
(a, b, c) = x
The same number of variables must be on the left side as on the right side. This
unpacking can be very useful if you are provided with a sequence variable (say as an
argument to a function) and want to access the values within it. For convenience, the
enclosing parentheses are not required, so the above assignment could also be written
as a, b, c = 1, 2, 3.
Multiple assignment
Jython supports the use of multiple assignment. For example, the following sets c to 1,
b to c (or 1), and a to b (also 1).
a = b = c = 1
Augmented assignment
Jython supports augmented assignment, which combines operators with assignment.
The general form is v <op>= expression, which is equivalent to v = v <op>
expression, except that v is evaluated only once (which can be important in a
subscripted variable).
+=
-=
*=
/=
%=
**=
<<=
>>=
&=
|=
^=
The if statement
The if, elif, and else statements provide basic decision capability. The test
expressions evaluate to false (None, 0 or empty) or true (not-0 or not-empty).
if expression: statement
-- or --
if expression:
block
Here's an example:
if expression: statement
else: statement
-- or --
if expression:
block
else:
block
Here's an example:
if x >= 0:
result = fac(x)
else:
print x, "is invalid for a factorial"
if expression: statement
elif expression: statement
:
else: statement
-- or --
if expression:
block
elif expression:
block
:
else:
block
The elif clause can repeat. The else clause is optional. Here's an example:
if x == 0:
doThis()
elif x == 1:
doThat()
elif x == 2:
doTheOtherThing()
else:
print x, "is invalid"
Conditional expressions
Most languages based on C, including C++ and the Java language, support a
conditional expression. These expressions return a choice of sub-expressions. They
are especially useful to avoid the use of repeated targets. This is important if the target
contains complex expressions, such as subscripts. Conditional expressions have the
form
Jython does not support conditional expressions directly; instead it employs this form:
-- or --
You can approximate the Java conditional expression form in Jython using the and,
and or operators, as shown here:
Note that this form works only if true_expression and false_expression do not
themselves evaluate to false values (such as None, 0, or an empty sequence or map).
If that is the case, use the if-else form.
:
# define the function to handle each unique case
def case1(...): return ...
def case2(...): return ...
:
def caseN(...): return ...
-- or --
-- or --
while expression:
block
else:
block
The else clause, which is optional, is executed only if the while clause ends normally
(that is, not with a break statement). It is not typically used.
Example:
x = 10
while x > 0:
process(x)
x -= 1
-- or --
The else clause, which is optional, is executed only if the for clause ends normally
(that is, not with a break statement). It is not typically used.
Example:
for c in "String":
processCharacter(c) # process the chars in turn
-- or --
values = (1,2,5,7,9,-1)
for v in values:
process(v) # process the values supplied
-- or --
for i in range(10):
print i # print the values 0 to 9 on separate lines
-- or --
In the above code, the use of for i in range(limit) provides for the typical
for-loop or do-loop iteration of most languages. Note also that the keys will not
necessarily come out in the order supplied.
break
Here's an example:
for i in range(100):
d = getData(i)
if not valid(d): break # can't continue
processData(d)
Likewise, it may be occasionally necessary to skip the rest of the loop body and begin
the next iteration early. The continue statement provides this behavior. The
statement has the following form:
continue
Here's an example:
for i in range(100):
: # *** some preliminary work ***
if not valid(i): continue # can't process this one
: # *** some other stuff ***
Updating a sequence
You must take special care when updating (that is, inserting or deleting entries from) a
sequence while iterating over it, as this can cause the iteration indexes to change
unpredictably. I recommend you make a copy of the sequence to iterate over, as
shown below:
Local or global variables can be deleted; this removes the variable from the
namespace (it does not delete the object the variable refers to). The del statement
also supports the slice notation.
Assuming "l" is the list [1,2,3,4,5], d is the dictionary {1:"one", 2:"two", 3:"three"} and x
is some class instance, some example del statements are as follows:
Example Comment(s)
del l[0] Removes the first element
del l[1:3] Removes the second through third elements
del l[::2] Removes the even elements
del l[:] Removes all the elements
del d[1] Removes the element with key 1
del x.attr1 Removes the attribute attr1
var = [1,2,3] Removes the variable var from its namespace
:
del var
Jython provides many built-in and library functions for you to use (see Appendix E:
Built-in functions on page 72 and
Appendix F: Jython library summary on page 76 ). Built-in
functions can be used without importing them; library function must first be imported.
Jython goes beyond many languages, including the Java language, by making
functions first-class objects that can be manipulated just like other objects (and most
specifically, objects that can be stored in collections and passed as arguments to other
functions).
-- or --
Within a given scope (module, function, or class), each function name should be
unique. The function name is really a variable bound to the function body (similar to
any other assignment). In fact, multiple variables can be defined to reference the same
function. The function body can be a single (frequently a return) statement or (more
commonly) a block of statements.
Example Comment(s)
def x(a, b, c) Defines a function with three required positional arguments.
def x(a, b, Defines a function with three arguments, the last of which is
c=1) optional with a default value of 1.
def x(a=3, Defines a function with three arguments, all of which are
b=2, c=1) optional and have default values.
def x(p1, p2, Defines a function with two positional parameters and two
kw1=1, kw2=2) keyword (optional) parameters. When declared, all optional
(=value) parameters must follow all non-optional
parameters. When this function is called, the keyword
parameters, if provided, can be specified by name and in
any order after positional parameters.
def x(p1, p2, Defines a function with two required positional parameters
*v) and an indeterminate number of variable parameters. The v
variable will be a tuple.
def x(p1, p2, Defines a function with two required positional parameters
**kw) and an indeterminate number of keyword parameters. The
kw variable will be a dictionary.
def x(p1, p2, Defines a function with two required positional parameters
*v, **kw) and an indeterminate number of positional and keyword
parameters. The v variable will be a tuple. The kw variable
will be a dictionary.
Because the value after the equals sign is evaluated only when the function is defined
(not each time it is called), the list in the second example above will be shared across
all calls to the function. This is usually not the desired behavior. The first example gets
Anonymous functions
You can define anonymous functions, called lambda functions. Anonymous functions
are one-line functions that are typically used as arguments to other functions. These
functions are declared using the following form:
The args list is the same as the one described in Specifying function arguments on
page 55 . You should have at least one argument per lambda function. The expression
value is returned by the function.
return expression
-- or --
return
Function calls
Functions are called by use of the call operator, which is a parenthesized list
following a function reference. For example, if f is a function, then f(...) calls the
function. If the function definition supports arguments, then the call may include
parameters, as shown in the examples below:
Note that spaces are optional between parameter declarations and arguments. Adding
a space between each is recommended for increased readability.
return x
print abs(-10) # prints 10
def factorial(x):
"calculate the factorial of a number"
if x < 0:
raise ValueError, "negative factorial not supported"
if x < 2:
return 1
return long(x) * factorial(x-1)
y = b
z = c # local z variable
f1(1, 2, 3)
print x, y, z # prints: 10, 20, 30
Note that as long as it is not re-bound locally, a global variable can be read without first
declaring it to be a global. Thus the global statement is only required to assign to a
global variable.
Generic functions
Similar to in Smalltalk functions, Jython functions are generic in that any type can be
passed in for each argument. This makes functions extremely flexible. Generic
functions work as long as the operations performed on the arguments in the function
are valid for the argument's actual type. For example, with these functions' definitions
# See Part 2 of this tutorial for the definition of the UserList class
from UserList import *
:
data = None # undefined until setData called
prevdata = []
Nested functions
Unlike many other languages, including the Java language, Jython allows functions to
be defined inside of other functions. The nested (or local) functions can help to reduce
the scope of functions. Here's an example:
def square(x):
return x ** 2 # this x is different from function x
y *= square(c)
return x
The nested function has no visibility into the variables in the containing function. If the
nested function must use these values, pass them into the function as arguments. For
def sum(data):
# cannot access calc's namespace (x, a, b, c, or sum) here
print locals()
return data['a'] + data['b'] + data['c']
x += sum(locals())
return x
print calc(10,20,30)
prints
def makeSq(n):
def sq(x=n): # n's value is saved as the parameter x value
return x ** 2
return sq
sq2 = makeSq(2)
print "2*2=%i" % sq2() # prints: 2*2=4
sq10 = makeSq(10)
print "10*10=%i" % sq10() # prints: 10*10=100
Functional programming
Like Lisp and Smalltalk, Jython supports a limited form of functional programming.
Functional programming uses the first-class nature of Jython functions and performs
operations on functions and data structures. The built-in functional programming
services are shown below:
Using functions like map, reduce, and filter can make processing sequences (that
is, strings, lists, and tuples) much easier. These functions are higher-order functions
because they either take functions as arguments or return them as results.
def fac(x):
return reduce(lambda m,n: long(m)*n, range(1,x))
def body1(count):
# any body here
:
def body2(x,y,z):
# any body here
:
Here's an example of how we'd use the above filter to select some employees:
# returns: [Jose]
hasChildren = filter(lambda e: e.children, employees)
# returns: []
over65 = filter(lambda e: e.age>65, employees)
# returns: [Mary]
isProgrammer = filter(lambda e: \
e.title and e.title.lower().find('prog') >= 0, employees)
Summary
In this first half of the two-part "Introduction to Jython" tutorial, you've learned the
concepts and programming basics of working with Jython, including access options
and file compilation, syntax and data types, program structure, procedural statements,
and functional programming with Jython.
In the second half of this tutorial, we will begin to wrestle with some of the more
advanced aspects of the language, starting with a conceptual and hands-on
introduction to object-oriented programming in Jython. You'll also learn about
debugging, string processing, file I/O, and Java support in Jython. The tutorial will
conclude with an exciting, hands-on demonstration of how to build a working GUI app
in Jython.
It's a good idea to take the second part of the tutorial as soon as you can, while the
concepts from Part 1 are still fresh in your mind. If you prefer to take a break in your
studies, you might want to use the time to explore the appendices included with Part 1
(Appendices on page 68 ), or check out some of the references included in the
Resources and feedback on page 66 section.
• Take the second part of this tutorial "Introduction to Jython, Part 2: Programming
essentials" (developerWorks, April 2004).
• Jython modules and packages enable reuse of the extensive standard Java libraries.
Learn more about the Java libraries (and download the current version of the JDK)
on the Sun Microsystems Java technology homepage.
• You'll find the Python Library Reference, Python docs, and Python tutorials on the
Python home page.
• Try your hand at using Jython to build a read-eval-print-loop, with Eric Allen's "Repls
provide interactive evaluation" (developerWorks, March 2002).
• For a solid introduction to Jython, see Samuele Pedroni and Noel Rappin's Jython
Essentials (O'Reilly, March 2002).
• Python Programming with the Java Class Libraries is a good introduction to building
Web and enterprise applications with Jython (Richard Hightower, Addison Wesley,
2003).
• You'll find articles about every aspect of Java programming in the developerWorks
Java technology zone.
• Also see the Java technology zone tutorials page for a complete listing of free
Java-focused tutorials from developerWorks.
Feedback
Please send us your feedback on this tutorial!
s.title()
s.join(seq) Join the strings in " ".join(("hello", "goodbye") -->
seq with s as the "hello goodbye"
separator
s.splitlines({keep}) Split s into lines, if "one\ntwo\nthree".splitlines() -->
keep true, keep ["one", "two", "three"]
the newlines
s.split({sep {, Split s into "words" "one two three".split() --> ["one",
max}}) using sep (default "two", "three"]
of white space) for
up to max times
s.ljust(width) Left, right or center "xxx".rjust(8) --> " xxx"
justify the string in
s.rjust(width) a field width wide. "xxx".center(8) --> " xxx "
s.center(width) Fill with 0. str(10).zfill(10) -->
"0000000010"
s.zfill(width)
s.lstrip() Remove leading " xxx ".strip() --> "xxx"
(and/or trailing)
s.rstrip() white space
s.strip()
s.translate(str Translate s using "ab12c".translate(reversealpha,
{,delc}) table, after "0123456789") --> "cba"
removing any
characters in delc.
str should be a
string with length
== 256
s.replace(old, new Replaces all or "11111".replace('1', 'a', 2) -->
{, max}) max occurrences "aa111"
old string old with
string new
Note: other methods are supported, for a complete list see the Python Library
Reference (Resources and feedback on page 66 ). Also note that by including the
string module, many (but not all) of these methods can also be called as functions, i.e.-
string.center(s, 10) is the same as s.center(10).
Variable Comment(s)
digits The decimal, octal, and hexadecimal digits
octdigits
hexdigits
lowercase The lowercase alphabet, the uppercase alphabet,
and the union of them
uppercase
letters
whitespace The legal white space characters
[3,2,1]
l.sort({cmp}) Sorts the list (in-place); The cmp [1,4,3,2].sort() -->
function is used to sort the items. [1,2,3,4]
The cmp function takes two
argument and returns <0, 0, >0
Method Comment(s)
m.clear() Empty the map
m.copy() Make a shallow copy of the map
m.has_key(k) Test to see if a key is present
-- or --
k in m
m.items() Get a list of the key/value tuples
m.keys() Get a list of the keys
m.values() Get a list of the values (may have duplicates)
m1.update(m2) add all the items in m2 to m1
m.get(k{, default}) Get the value of k, return default/KeyError if
missing; same as get, but set a persistent default
m.setdefault(k, default) value
m.popitem() Get and remove some item, used during iteration
over the map. Example:
Most libraries that are written in Python and do not depend on operating system
specific services are supported without change. Many of these libraries are shipped
with Jtyhon. Libraries written in C must be converted; many of the core C libraries have
been converted and are shipped with Jython.
Jython also has a few unique libraries of its own. These libraries supplement the
extensive API libraries provided by Java itself. For more details on these libraries, read
the source files (in <jython_install_dir>/Lib/<lib_name>.py) or see the Python Library
Reference (Resources and feedback on page 66 ).
Some of the more interesting external libraries supplied with Jython include:
Note: I do not claim the above library modules work or are error free on Jython,
especially when you are not running on a UNIX system. Try them interactively before
you decide to code to them.
For more information on types see the Python Library Reference (Resources and
feedback on page 66 ).
Note: more details on the structure and options of the format item can be found in the
Python Library Reference (Resources and feedback on page 66 ). Use of case in
format characters (for example, X vs x causes the symbol to show in matching case.
Colophon
This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial
generator. The open source Toot-O-Matic tool is an XSLT stylesheet and several XSLT
extension functions that convert an XML file into a number of HTML pages, a zip file, JPEG
heading graphics, and two PDF files. Our ability to generate multiple text and binary formats
from a single source file illustrates the power and flexibility of XML. (It also saves our
production team a great deal of time and effort.)